我的工作流程使用 MySQL 驱动程序执行查询并将结果集保存在 arraylist 中,并从 arraylist 中填写 Excel 工作表中的详细信息(使用 Apache poi(
问题如果数组列表包含空,则在Excel工作表中的插入过程中出现空指针异常。
我的代码
resultSet = statement.executeQuery(query);
while (resultSet.next()){
Date lastResponse = resultSet.getDate("lastresponse");
response.add(lastResponse);
}
上面的数组列表包含以下值
2017-04-20, 2017-04-25, 2017-04-24, null, 2017-08-03
现在我尝试在Excel工作表中插入上述值(全部(
for (int j = 0; j <= response.size(); j++) {
row = sheet.getRow(j + 2);
cell = row.createCell(1);
cell.setCellValue(Cell.CELL_TYPE_STRING);
cell.setCellValue(response.get(j).toString());
}
运行时Exception in thread "main" java.lang.NullPointerException
预期的解决方案
想要在相应的单元格中插入空值或需要替换连字符符号而不是空。
您的代码只需要一个空检查。空值可以通过以下行进行检查
response.get(j)!=null
完成此检查后,您可以根据需要更改代码。
for (int j = 0; j <= response.size(); j++) {
row = sheet.getRow(j + 2);
cell = row.createCell(1);
cell.setCellValue(Cell.CELL_TYPE_STRING);
response.get(j)!=null ? cell.setCellValue(response.get(j).toString()) : cell.setCellValue("Null");
}
response = response.stream().map(x -> (x == null)? "-":x).collect()