解析Excel中通过POI和靶细胞是空的,有时解析OK,有时扔nullpointexception [英] Parse Excel by poi and target cell is empty sometimes parse ok sometimes throw nullpointexception

查看:227
本文介绍了解析Excel中通过POI和靶细胞是空的,有时解析OK,有时扔nullpointexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现解析的一个奇怪的现象被POI脱颖而出。见code

I found a strange phenomenon of parse excel by poi. See code

goods.subtitle = row.getCell(headerNameIndexMap.get("subtitle")).getStringCellValue();

解析字幕栏和设定值对象。有两个Excel,无论是字幕栏是空的,但是分析其中的一个就可以了,只是字幕属性为空,但是当解析另一个Excel,它会抛出异常:

parse subtitle column and set value to object. There are two excel, both subtitle column is empty, but parse one of them is ok, just subtitle property is null, but when parse another excel, it throws exception:

java.lang.NullPointerException

复制一些相同的名字列从成功中脱颖而出失败Excel中,前解析失败列可以解析正常,但突然在故障Excel中的非空列突然地分析失败后,扔NullPointException。然后复制成功,从同一个名字列练成失败Excel时,Excel的失败现在可以成功地解析。

After copying some same name column from success excel to fail excel, before parse failed column could parse ok, but suddenly a non empty column in fail excel suddenly parse failed, throw NullPointException. Then copying the same name column from success excel to fail excel, the fail excel now can parse successfully.

如果我从故障Excel中复制解析失败列成功脱颖而出,它还是失败地分析。但复制另一个列成功脱颖而出并粘贴特殊,只检查格式的失败列时,它会分析确定。

And if I copy the parsed fail column from fail excel to success excel, it still parse failed. But when copy another column in success excel and paste special and only check Formats to the fail column, it will parse ok.

这是什么原因?

推荐答案

由于每的 Apache的POI的JavaDocs,Row.getCell(INT)可能返回null。空电池是一个没有价值,没有造型,因此没有记录在文件

As per the Apache POI JavaDocs, Row.getCell(int) may return Null. A null cell is one that has no value and no styling, and hence is not recorded in the file

您code将无法为空白单元格,并为空白单元格(previously举行了值,但不再),并为数字单元。因此,坦率地说,大多数情况下,...

Your code will therefore fail for empty cells, and for blank cells (previously held a value but no longer), and for numeric cells. So, frankly, most cases...

您或许应该改变你的code更是这样的:

You should probably change your code to more like this:

DataFormatter formatter = new DataFormatter();

Cell cell = row.getCell(headerNameIndexMap.get("subtitle"), Row.    RETURN_BLANK_AS_NULL);
if (cell == null) {
   // No value here, handle
} else {
   String subtitle = formatter.formatCellValue(cell);
}

这将处理空白单元格,空细胞,并会给你一个字符串格式化为数字单元格

That will handle empty cells, null cells, and will give you a string for formatted numeric cells

这篇关于解析Excel中通过POI和靶细胞是空的,有时解析OK,有时扔nullpointexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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