本文介绍了Apachi POI - 单元格 setCellValue 抛出 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试更新现有的 excel 文件时遇到以下错误:
When I am trying to update existing excel file I am encountering following error:
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 cell does not exist yet, so getCell
returns null
.
如果它不存在,您必须检测到并创建单元格,使用 createCell
方法:
You must detect this and create the cell if it doesn't exist, with the createCell
method:
if (cell == null)
{
cell = sheet.getRow(0).createCell(3);
}
// Then set the value.
cell.setCellValue("onu");
或者,有 getCell
的重载,您可以在其中指定 MissingCellPolicy
以便空白 Cell
如果它不存在,则会自动创建:
Alternatively, there is an overload of getCell
where you can specify a MissingCellPolicy
so that a blank Cell
is automatically created if it didn't already exist:
cell = sheet.getRow(0).getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
这篇关于Apachi POI - 单元格 setCellValue 抛出 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!