Apachi POI - 单元格 setCellValue 引发 NullPointerException

问题描述 投票:0回答:2

当我尝试更新现有 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();
java apache-poi
2个回答
14
投票

该单元尚不存在,因此

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);

0
投票

试试这个。它对我有用

    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);
© www.soinside.com 2019 - 2024. All rights reserved.