java 在读取 Excel 工作表时,如何知道单元格是否返回空值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15014231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:11:49  来源:igfitidea点击:

How do I know if a cell returns a null value while reading an Excel Sheet?

javaapache-poi

提问by TheRookierLearner

I am reading values from some specific cells in an excel sheet. Those cells generally contain String but sometimes they may be blank (thus may return a blank or a null). I am using the following code to get the cell data:

我正在从 Excel 工作表中的某些特定单元格中读取值。这些单元格通常包含字符串,但有时它们可​​能是空白的(因此可能返回空白或空值)。我正在使用以下代码来获取单元格数据:

Cell cellValue = row.getCell(10, Row.RETURN_NULL_AND_BLANK);
List.add(cellValue.getStringCellValue());

However, when I run this code I get a NullPointerException. Can anybody point out what is wrong and should be added?

但是,当我运行此代码时,我得到一个NullPointerException. 任何人都可以指出什么是错误的,应该添加吗?

Note: I am deliberately using Row.RETURN_NULL_AND_BLANKand not MissingCellPolicy.RETURN_NULL_AND_BLANKbecause using the latter was giving me an error.

注意:我是故意使用Row.RETURN_NULL_AND_BLANK而不是MissingCellPolicy.RETURN_NULL_AND_BLANK因为使用后者给了我一个错误。

回答by dan

You need to test the cellValueif it is not null, since using Row.RETURN_NULL_AND_BLANKwill return nullin cases where you are trying to access a missing cell.

您需要测试cellValue它是否不为空,因为在您尝试访问丢失的单元格的情况下usingRow.RETURN_NULL_AND_BLANK将返回null

You are getting a NullPointerExceptionbecause 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());

回答by TheRookierLearner

@dan - Thanks for your reply. That indeed helped. I modified my code as follows and I am not getting that exception now:

@dan - 感谢您的回复。那确实有帮助。我按如下方式修改了我的代码,现在我没有收到该异常:

Cell cellValue = row.getCell(10, Row.CREATE_NULL_AS_BLANK);
if(cellValue.getStringCellValue().equals("")){
    List.add("NOT FOUND");
}
else {
    List.add(cellValue.getStringCellValue());
}

回答by Mohamed Makthum

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.

如果单元格值为空,希望这会有所帮助,那么您不要将单元格值添加到您的列表中。