Apachi POI-单元格setCellValue引发NullPointerException [英] Apachi POI - Cell setCellValue thows NullPointerException

查看:1613
本文介绍了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.

您必须使用

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

或者,还有

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆