Home > Software engineering >  sheet gives me null pointer apache poi
sheet gives me null pointer apache poi

Time:11-05

I want to create a file .xls but when I set a value it gives me null pointer. this is my code :

(the file xls is empty at start and I need to create two sheet from the code):

Workbook wb = new HSSFWorkbook();
       Sheet general=wb.createSheet("General"); 
    
    //after this line it gives me null point
                Row row = general.getRow(0);    
                Cell cell = row.getCell(1);   

It seems that "general" is null.Anyone can help me?

CodePudding user response:

getRow(0) throws Exception because row-0 does not exist. you need to create the row in the first place :

Row row = general.createRow(0);

CodePudding user response:

Row row = general.getRow(0) will give you null as the row doesn't exist. Only once it is created using general.createRow(0), it can be used. So once rwo at 0 is created, if you call getRow(0), it will return that row. And only a non-null row can have a cell.

You can create your own util method like below which can be used to get the row if not created.

public Row getRow(Sheet sheet, int rowNo)
{
    Row row = sheet.getRow(rowNo);
    if(row == null)
    {
        row = sheet.createRow(rowNo);
    }
    return row;
}

row.getCell would also face similar problem. It should create cell first. Or you can use this.

Cell cell = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
  • Related