使用POI getCell 获取空的单元格之后在使用的时候报 NullPointerException

时间:2020-11-28 16:42:12

解决办法,在得到cell之后先判断cell是否为空,然后再进行逻辑处理。

得到的cell建议使用去除策略(如左对齐,居中等)的cell,不然有可能受到策略影响而导致结果异常。

org.apache.poi.ss.usermodel.Row.MissingCellPolicy policy = org.apache.poi.ss.usermodel.Row.RETURN_NULL_AND_BLANK;

for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null) {
// The spreadsheet is empty in this cell
} else {
// Do something useful with the cell's contents
}
}

参考资料:

How to avoid NullPointerException with an empty cell using POI?

Iterate over cells, with control of missing / blank cells