Home » excel » java – Exporting grid in excel in Vaadin 14

java – Exporting grid in excel in Vaadin 14

Posted by: admin May 14, 2020 Leave a comment

Questions:

I created the grid in vaadin. Now I need to export that grid in excel. I am using Vaadin Exporter but I am not able to export the grid using exporter.

Grid<Transaction> grid = new Grid<>(Transaction.class);
Button exportInExcel = new Button("Export in excel", event -> exportInExcel());

private void exportInExcel() {
    new Anchor(new StreamResource("my-excel.xlsx", Exporter.exportAsExcel(grid)), "Download As Excel");
}

How can I export the grid in excel in vaadin 14

How to&Answers:

That work for me:

@Route(value = "erwachsenentraining", layout = MainLayout.class)
@PageTitle(Constants.ERWACHSENENTRAINING)
@Secured(Role.ADMIN)
public class ErwachsenenTraining extends VerticalLayout {

    private ErwachseneRepository erwachseneRepository;
    Grid<Erwachsene> grid;

    public ErwachsenenTraining(ErwachseneRepository erwachseneRepository) {
        this.erwachseneRepository = erwachseneRepository;

        grid = new Grid();
        ListDataProvider<Erwachsene> dataProvider = DataProvider.ofCollection(erwachseneRepository.findAll());
        grid.setDataProvider(dataProvider);
        grid.addColumn(Erwachsene::getEmail).setKey("email").setWidth("270px").setHeader("Email").setFlexGrow(5);
        grid.addColumn(u -> u.getFirstName() + " " + u.getLastName()).setKey("firstName").setHeader("Name").setWidth("200px").setFlexGrow(5);
        grid.addColumn(Erwachsene::getRole).setKey("role").setHeader("Role").setWidth("150px");

        add(grid);
        add(new Anchor(new StreamResource("Erwachsenen_Training.xlsx", Exporter.exportAsExcel(grid)), "Download als Excel"));
    }
}

// Print
// JavaScript.getCurrent().execute("print();");