Apache POI - Cell setCellValue抛出NullPointerException

时间:2013-12-20 01:39:05

标签: java apache-poi

当我尝试更新现有的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();

1 个答案:

答案 0 :(得分:8)

该单元格尚不存在,因此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);

{{1}}