Apachi POI - Cell setCellValue thows NullPointerException

前端 未结 1 1231
南旧
南旧 2021-01-21 00:47

When I am trying to update existing excel file I am encountering following error:

Exception in thread \"main\" java.lang.NullPointerException
    at xltest.main(         


        
1条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-21 01:43

    The cell does not exist yet, so getCell returns null.

    You must detect this and create the cell if it doesn't exist, with the createCell method:

    if (cell == null)
    {
        cell = sheet.getRow(0).createCell(3);
    }
    // Then set the value.
    cell.setCellValue("onu");
    

    Alternatively, there is an overload of getCell where you can specify a MissingCellPolicy so that a blank Cell is automatically created if it didn't already exist:

    cell = sheet.getRow(0).getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
    

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