可以在 Vaadin 中将 JPA 存储库下载为 CSV 文件吗?

Possible to download JPA repository in Vaadin as CSV file?

假设我们已经定义了一个实体并且它连接到一个数据库。现在我们可以使用存储库访问数据库了。

@Autowired
private DataLoggRepository dataLoggRepository;

如果我想从数据库中获取所有行并下载它。然后我可以写这段代码:

List<DataLogg> dataLoggers = dataLoggRepository.findAll();

现在,如何以正确的方式在 Vaadin 中将对象 dataLoggers 下载为 CSV 文件?

在这里你可以看到如何创建一个link来下载文件:

Anchor csvLink = new Anchor(new StreamResource("file.csv",
                 () -> {
                     String csvString = ...// create the csv
                     return new ByteArrayInputStream(csvString.getBytes());
                 }), "Download CSV");

csvLink.getElement().setAttribute("download", true);

要创建 CSV,您有多种选择,例如 OpenCSV 或直接从 SQL 查询创建 CSV。

这是一个工作示例

        // Download all data
        Anchor download = new Anchor(); // Add this to the layout
        loggerId.addValueChangeListener(e-> {
            String fileName = String.valueOf(loggerId.getValue()) + ".csv";
            List<DataLogg> selectedLogger = dataLoggRepository.findByLoggerId(loggerId.getValue());
            download.setHref(getStreamResource(fileName, selectedLogger));
        });
        download.getElement().setAttribute("download",true);
        download.add(new Button("Download", new Icon(VaadinIcon.DOWNLOAD_ALT)));

函数

public StreamResource getStreamResource(String filename, List<DataLogg> selectedLogger) {
        // Create a large CSV file in a form of StringBuilder and then convert it all to bytes
        StringWriter stringWriter = new StringWriter();
        stringWriter.write("id, dateTime, DO0, DO1, DO2, DO3, AI0, AI1, AI2, AI3, loggerId, samplingTime\n");
        for (int i = 0; i < selectedLogger.size(); ++ i) {
            DataLogg dataLogg = selectedLogger.get(i);
            String row = dataLogg.getId() + "," +
            dataLogg.getDateTime() + "," +
            dataLogg.getDO0() + "," +
            dataLogg.getDO1() + "," +
            dataLogg.getDO2() + "," +
            dataLogg.getDO3() + "," +
            dataLogg.getAI0() + "," +
            dataLogg.getAI1() + "," +
            dataLogg.getAI2() + "," +
            dataLogg.getAI3() + "," +
            dataLogg.getLoggerId() + "," +
            dataLogg.getSamplingTime() + "\n";
            stringWriter.write(row);
        }

        // Try to download
        try {
            byte[] buffer = stringWriter.toString().getBytes("UTF-8");
            return new StreamResource(filename, () -> new ByteArrayInputStream(buffer));
        } catch (UnsupportedEncodingException e) {
            byte[] buffer = new byte[] {0};
            return new StreamResource(filename, () -> new ByteArrayInputStream(buffer));
        }
    }