当我尝试更新现有 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();
该单元尚不存在,因此
getCell
返回 null
。
createCell
方法: 创建该单元格
if (cell == null)
{
cell = sheet.getRow(0).createCell(3);
}
// Then set the value.
cell.setCellValue("onu");
getCell
的重载,您可以在其中指定 MissingCellPolicy
,以便自动创建空白 Cell
(如果尚不存在):
cell = sheet.getRow(0).getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
试试这个。它对我有用
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sh = wb.getSheetAt(0);
Row row1 = sh.createRow(row);
Cell cell = row1.createCell(column);
if(cell == null) {
cell = sh.getRow(row).createCell(column);
}
sh.getRow(row).createCell(column).setCellValue(value);