Parse Excel by poi and target cell is empty sometimes parse ok sometimes throw nullpointexception

心已入冬 提交于 2019-12-20 04:39:24

问题


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

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

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

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.

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.

What is the reason?


回答1:


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

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...

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



来源:https://stackoverflow.com/questions/33918243/parse-excel-by-poi-and-target-cell-is-empty-sometimes-parse-ok-sometimes-throw-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!