[英]Apache POI SXSSF Shows NullPointerException on flush rows
I have 500 rows in my table.我的表中有 500 行。 When I'm using
setRandomAccessWindowSize(1000)
it's working fine.当我使用
setRandomAccessWindowSize(1000)
它工作正常。 Data is exported successfully in Excel file from resultset, But when I use setRandomAccessWindowSize(100)
it is giving me a NullPointerException I don't know what I'm doing wrong.数据从结果集中在 Excel 文件中成功导出,但是当我使用
setRandomAccessWindowSize(100)
它给了我一个NullPointerException我不知道我做错了什么。 Please suggest proper way to do this.请建议正确的方法来做到这一点。
Here's my code:这是我的代码:
workbook = new SXSSFWorkbook(100); //SXSSF workbook
workbook.setCompressTempFiles(true);
SXSSFSheet spreadsheet = workbook.createSheet("Sheet1"); //Generating Excel file
SXSSFRow row;
SXSSFCell cell;
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();//Create font
font.setBold(true);//Make font bold
style.setFont(font);//set it to bold
int y = 1;
if (rs.isBeforeFirst() == true) {
while (rs.next()) {
row = spreadsheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("SR NO");
cell.setCellStyle(style);
for (int s = 1; s <= rsmd.getColumnCount(); s++) {
cell = row.createCell(s);
cell.setCellValue(rs.getMetaData().getColumnName(+s).toUpperCase());
cell.setCellStyle(style);
}
row = spreadsheet.createRow(y);
cell = row.createCell(0);
cell.setCellValue(y + "");
//spreadsheet.autoSizeColumn(0);
for (int x = 1; x <= rsmd.getColumnCount(); x++) {
cell = row.createCell(x);
String address = new CellReference(cell).formatAsString();
cell.setCellValue(address);
cell.setCellValue(rs.getString(+x));
//spreadsheet.autoSizeColumn(x);
}
y++;
}
FileOutputStream out = new FileOutputStream(new File(destination));
workbook.write(out);
out.close();
workbook.dispose();
I have updated while loop in above code.我在上面的代码中更新了 while 循环。 It was writing 0th row multiple times.
它多次写入第 0 行。 That's why on 101th row it was giving NullPointer exception as 0th row is already flushed.
这就是为什么在第 101 行它给出 NullPointer 异常,因为第 0 行已经被刷新。
Here's my fix-这是我的修复-
if (rs.isBeforeFirst() == true) {
while (rs.next()) {
//writing columns
if (rs.isFirst()) {
row = spreadsheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("SR NO");
cell.setCellStyle(style);
for (int s = 1; s <= rsmd.getColumnCount(); s++) {
cell = row.createCell(s);
cell.setCellValue(rs.getMetaData().getColumnName(+s).toUpperCase());
cell.setCellStyle(style);
}
}
//Writing data
row = spreadsheet.createRow(y);
cell = row.createCell(0);
cell.setCellValue(y + "");
//spreadsheet.autoSizeColumn(0);
for (int x = 1; x <= rsmd.getColumnCount(); x++) {
cell = row.createCell(x);
cell.setCellValue(rs.getString(+x));
//spreadsheet.autoSizeColumn(x);
}
y++;
}
FileOutputStream out = new FileOutputStream(new File(destination));
workbook.write(out);
out.close();
workbook.dispose();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.