[英]How do I know if a cell returns a null value while reading an Excel Sheet?
I am reading values from some specific cells in an excel sheet. 我正在读取excel表中某些特定单元格的值。 Those cells generally contain String but sometimes they may be blank (thus may return a blank or a null). 这些单元格通常包含String,但有时它们可能是空白的(因此可能返回空格或null)。 I am using the following code to get the cell data: 我使用以下代码来获取单元格数据:
Cell cellValue = row.getCell(10, Row.RETURN_NULL_AND_BLANK);
List.add(cellValue.getStringCellValue());
However, when I run this code I get a NullPointerException
. 但是,当我运行此代码时,我得到一个NullPointerException
。 Can anybody point out what is wrong and should be added? 任何人都可以指出什么是错的,应该加入吗?
Note: I am deliberately using Row.RETURN_NULL_AND_BLANK
and not MissingCellPolicy.RETURN_NULL_AND_BLANK
because using the latter was giving me an error. 注意:我故意使用Row.RETURN_NULL_AND_BLANK
而不是MissingCellPolicy.RETURN_NULL_AND_BLANK
因为使用后者会给我一个错误。
You need to test the cellValue
if it is not null, since using Row.RETURN_NULL_AND_BLANK
will return null
in cases where you are trying to access a missing cell. 如果cellValue
不为null,则需要测试它,因为在尝试访问缺少的单元格时,使用Row.RETURN_NULL_AND_BLANK
将返回null
。
You are getting a NullPointerException
because the 10-th column on a specified row is missing. 您将收到NullPointerException
因为缺少指定行上的第10列。
If you need to handle differently the missing vs. blank cases you can use the following: 如果您需要处理丢失与空白案例的不同,您可以使用以下内容:
Cell cellValue = row.getCell(10, Row.RETURN_NULL_AND_BLANK);
if (cellValue == null)
List.add("CELL NOT FOUND");
else if("".equals(cellValue.getStringCellValue().trim()))
List.add("MISSING CONTENT");
else
List.add(cellValue.getStringCellValue());
@dan - Thanks for your reply. @dan - 谢谢你的回复。 That indeed helped. 这确实有帮助。 I modified my code as follows and I am not getting that exception now: 我按如下方式修改了代码,现在我没有得到异常:
Cell cellValue = row.getCell(10, Row.CREATE_NULL_AS_BLANK);
if(cellValue.getStringCellValue().equals("")){
List.add("NOT FOUND");
}
else {
List.add(cellValue.getStringCellValue());
}
hey there , why cant you add the null pointer check like 嘿那里,为什么你不能添加空指针检查
if(null!=cellValue)
{
List.add(cellValue.getStringCellValue());
}
hope this helps if the cell value is null then you dont add the cell value to your list. 希望这有助于如果单元格值为null,那么您不会将单元格值添加到列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.