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

前端 未结 1 810
醉酒成梦
醉酒成梦 2021-01-24 21:32

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

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


        
相关标签:
1条回答
  • 2021-01-24 22:08

    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

    0 讨论(0)
提交回复
热议问题