Getting null pointer exception in creating cell in Apache POI

做~自己de王妃 提交于 2019-12-12 09:14:55

问题


I am getting a null pointer error everytime I ran my code (below) and it points to the line specified with two asterisk.

public void writeSomething(XSSFWorkbook wb){
        for (String elem: listOfSheetNames){
            if (elem.equals("Sheet2")){
                sheet = wb.getSheet(elem); //sheet is of type XSSFSheet
                XSSFRow row = sheet.getRow(0);
                **XSSFCell cell = row.getCell(1);

                if (cell == null){
                    cell = row.createCell(1);
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    cell.setCellValue("Apple");
                }                                       
            }
        }
    }

I am a new to apache poi and am just trying to write data to a blank cell in a 2nd excel sheet (Sheet2). Did I do something wrong here?


回答1:


Unfortunately, the cell is currently null not a blank cell. Placing data on the specified sheet makes it blank. You might want to create the cell first then check if it is a blank cell rather than null.

**XSSFCell cell = row.createCell(1);

if (cell == Cell.CELL_TYPE_BLANK){
   cell.setCellType(Cell.CELL_TYPE_STRING);
   cell.setCellValue("Apple");
}   



回答2:


This would led to incompatible types.

Instead do this:

if (cell.getCellType() == Cell.CELL_TYPE_BLANK){
    cell.setCellType(Cell.CELL_TYPE_STRING);
    cell.setCellValue("Apple");
}   


来源:https://stackoverflow.com/questions/14227108/getting-null-pointer-exception-in-creating-cell-in-apache-poi

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