Apachi POI - Cell setCellValue引发NullPointerException

Onu*_*Onu 3 java apache-poi

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

Exception in thread "main" java.lang.NullPointerException
    at xltest.main(xltest.java:28)
Run Code Online (Sandbox Code Playgroud)

我的代码:

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();
Run Code Online (Sandbox Code Playgroud)

rge*_*man 10

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

你必须进行检测,并创建单元格,如果不存在的话,用createCell方法:

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

或者,您可以指定一个重载,getCellMissingCellPolicy以便Cell在尚不存在的情况下自动创建空白:

cell = sheet.getRow(0).getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Run Code Online (Sandbox Code Playgroud)

  • @Onu 如果某些答案解决了您的问题,请随时接受它作为解决方案。更多信息:[“如何接受答案?”](http://meta.stackexchange.com/a/5235) (2认同)