0

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

@Autowired
private DataLoggRepository dataLoggRepository;

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

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

现在,我怎样才能dataLoggers以适当的方式在 Vaadin 中将对象下载为 CSV 文件?

4

2 回答 2

1

在这里,您可以看到如何创建链接以下载文件:

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。

于 2020-06-10T13:26:36.070 回答
0

这是一个工作示例

        // 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));
        }
    }
于 2020-06-10T22:03:26.793 回答