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