当我尝试更新现有的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)
| 归档时间: |
|
| 查看次数: |
7596 次 |
| 最近记录: |