1
votes

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?

2
What line does the error occur? - Michael 'Maik' Ardan
@MichaelArdan Question clearly saying and it points to the line specified with two asterisk. ie **XSSFCell cell = row.getCell(1); - Smit
@smit Sorry didn't read read the phrase after (below) - Michael 'Maik' Ardan
its alright guys... my code actually worked after I placed some random bits of data in 2nd excel sheet. I don't know why that happened. Am just concerned right now that I would keep on doing that everytime I want to write in a new sheet :/ - dimas

2 Answers

5
votes

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");
}   
-1
votes

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");
}