【问题标题】:how to load data from database to excel sheet如何将数据库中的数据加载到excel表中
【发布时间】:2017-04-28 02:10:57
【问题描述】:

我需要将数据从数据库加载到 Excel 工作表。所以当我运行代码时抛出这个异常。 到目前为止,这就是我正在使用的。 数据库表名是 pettycash,所以我需要从这个表中加载数据。

private void excelTest(ActionEvent event) {
    try {
        String cococo = "select * from pettycash";
        ResultSet rs = database.DB_Connector.search(cococo);

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("pettycash");
        XSSFRow Header = sheet.createRow(0);
        Header.createCell(0).setCellValue("Petty ID");
        Header.createCell(1).setCellValue("pettycash_static_ammount");
        Header.createCell(2).setCellValue("pettycash_balance");
        Header.createCell(3).setCellValue("pettygiv_Date");
        Header.createCell(4).setCellValue("pettycash_status");
        Header.createCell(5).setCellValue("Rider_idRider");

        int index = 1;
        while (rs.next()) {

            XSSFRow row = sheet.createRow(index);
            row.createCell(0).setCellValue(rs.getString("idpettycash"));
            row.createCell(1).setCellValue(rs.getString("pettycash_static_ammount"));
            row.createCell(2).setCellValue(rs.getString("pettycash_balance"));
            row.createCell(3).setCellValue(rs.getString("pettygiv_Date"));
            row.createCell(4).setCellValue(rs.getString("pettycash_status"));
            row.createCell(5).setCellValue(rs.getString("Rider_idRider"));
            index++;

        }

        FileOutputStream fileout = new FileOutputStream("petycash.xlsx");
        wb.write(fileout);
        fileout.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • “当我运行代码时抛出这个异常”。在问题中发布完整的stack trace,并指出您发布的代码中的哪一行引发了异常。

标签: java javafx apache-poi javafx-2 javafx-8


【解决方案1】:

使用MemPOI查看此解决方案

private void excelTest(ActionEvent event) {
    try {
        String cococo = "select * from pettycash";
        PreparedStatement prepStmt = database.DB_Connector.preparedStatement(cococo);

        File file = new File("petycash.xlsx");

        new MempoiBuilder()
                .setFile(file)
                .addMempoiSheet(new MempoiSheet(prepStmt))
                .build()
                .prepareMempoiReportToFile()
                .get();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

【讨论】:

    【解决方案2】:

    您可以使用此library 手动执行您尝试执行的操作。一行代码:

    writer.writeAll(rs, includeHeaders);
    

    【讨论】:

    • 问题是询问如何将数据库文件写入 Excel 电子表格文件,以及为什么发布的代码会引发异常。 CSV 与 XLSX 不同。这没有回答所提出的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 2017-01-14
    相关资源
    最近更新 更多