问题
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