当我尝试更新现有的Excel文件时,遇到以下错误:

Exception in thread "main" java.lang.NullPointerException
    at xltest.main(xltest.java:28)

我的代码:
FileInputStream file = new FileInputStream(new File("C:\\Users\\onu\\test.xlsx"));

XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);

//Update the value of cell
Cell cell = sheet.getRow(0).getCell(3); // cell D1
cell.setCellValue("onu"); // line 28 which throws NPE

file.close();

FileOutputStream outFile =new FileOutputStream(new File("C:\\Users\\onu\\test.xlsx"));
workbook.write(outFile);
outFile.close();

最佳答案

该单元尚不存在,因此getCell返回null

您必须检测到它,并使用the createCell method创建一个不存在的单元格:

if (cell == null)
{
    cell = sheet.getRow(0).createCell(3);
}
// Then set the value.
cell.setCellValue("onu");

另外,还有an overload of getCell ,您可以在其中指定MissingCellPolicy,以便在空白Cell不存在时自动创建它:
cell = sheet.getRow(0).getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

10-01 19:20
查看更多