我需要将数据从数据库加载到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();
}
}
答案 0 :(得分:0)
使用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();
}
}
答案 1 :(得分:-1)
您可以使用此library执行您尝试手动执行的操作。一行代码:
writer.writeAll(rs, includeHeaders);