Hello,
I am having trouble figuring out how to export my Grid as a CSV file. I have tried to implement addons that work with Vaadin 8 but can’t seem to get them to work with Flow.
Thanks,
Josh
Hello,
I am having trouble figuring out how to export my Grid as a CSV file. I have tried to implement addons that work with Vaadin 8 but can’t seem to get them to work with Flow.
Thanks,
Josh
Hi, here’s an example:
package com.example;
import com.helger.commons.csv.CSVWriter;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Anchor;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.StreamResource;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;
@Route
public class MainView extends VerticalLayout {
private final CompanyService companyService = new CompanyService();
public MainView() {
Grid<Company> grid = new Grid<>(Company.class);
grid.setItems(getCompanies());
Anchor anchor = new Anchor(new StreamResource("grid.csv", this::getInputStream), "Export as CSV");
anchor.getElement().setAttribute("download", true);
add(grid, anchor);
}
private List<Company> getCompanies() {
return companyService.findAll();
}
private InputStream getInputStream() {
try {
StringWriter stringWriter = new StringWriter();
CSVWriter csvWriter = new CSVWriter(stringWriter);
csvWriter.writeNext("id", "name");
getCompanies().forEach(c -> csvWriter.writeNext("" + c.getId(), c.getName()));
return IOUtils.toInputStream(stringWriter.toString(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
Does this also work with Button / NativeButton?
Stefan Uebe:
Does this also work with Button / NativeButton?
I’m not sure. Maybe [this component]
(https://vaadin.com/directory/component/browser-opener) could help.
Hi, can you provide sample piece of code for working with Button to export as CSV?
byte[] bytes = "".getBytes(StandardCharsets.UTF_8);
StreamResource streamResource = new StreamResource("export data file name.csv", () -> new ByteArrayInputStream(bytes));
Anchor anchor = new Anchor(streamResource, null);
anchor.setTarget("_blank");
anchor.add(new ButtonFactory().text("download").clickListener(e -> close()).lumoSmall().lumoPrimary().get());
You can view my framework download part [link]
(https://github.com/CNBroderick/fluent-vaadin-flow/blob/master/src/main/java/org/bklab/crud/FluentCrudView.java#L127)
Grid Entity to Excel Xlsx Part: [link]
(https://github.com/CNBroderick/fluent-vaadin-flow/blob/master/src/main/java/org/bklab/export/xlsx/ExcelDataExporter.java)
Excel Xlsx to Entity Part: [link]
(https://github.com/CNBroderick/fluent-vaadin-flow/blob/master/src/main/java/org/bklab/flow/data/importer/excel/ExcelDataImporter.java)