如何从数据库加载数据到 excel sheet

how to load data from database to excel sheet

我需要将数据从数据库加载到 excel sheet。所以当我 运行 代码抛出这个异常。 到目前为止,这就是我正在使用的。 数据库 table 名称是 pettycash 所以我需要从这个 table.

加载数据
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();
    }
}

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

writer.writeAll(rs, includeHeaders);

使用 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();
    }
}