java - Apache POI SXSSF 在刷新行上显示 NullPointerException
问题描述
我的表中有 500 行。当我使用它时setRandomAccessWindowSize(1000)
,它工作正常。数据从结果集中成功导出到 Excel 文件中,但是当我使用setRandomAccessWindowSize(100)
它时,它给了我一个
NullPointerException我不知道我做错了什么。请提出正确的方法来做到这一点。
这是我的代码:
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();
解决方案
我在上面的代码中更新了 while 循环。它多次写入第 0 行。这就是为什么在第 101 行它给 NullPointer 异常,因为第 0 行已经被刷新。
这是我的解决方法-
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();
推荐阅读
- python - 在熊猫数据框中阅读谷歌电子表格
- android - 游标遍历空行
- php - 从子域路由重定向到根路由
- python - Python SMTP:将电子邮件合二为一
- java - 如何在 f(p) = (ap + b) mod 2 形式的函数中找到 a 和 b,知道给出的是纯文本 + 密文(蛮力)
- api - 企业搜索解决方案
- reactjs - Redux - mapDispatchToProps - TypeError:_this.props.setCurrentUserHandle 不是函数
- spring-boot - spring boot 2.0.2.RELEASE 与 spring 5.0.6.RELEASE NoSuchMethodError AbstractHandlerMapping.obtainApplicationContext
- postgresql - Postgres 中的并行函数执行
- css - 用作背景图像时如何缩放 CSS 精灵?