XSSF. NullPointerException

1.3k Views Asked by At
private void cleaner(Integer columnsCount, Integer rowsCount, Object object){
    int firstColumn=0;
    int firstRow=0;
    XSSFSheet sheet = workBook.getSheetAt(0);
    for (int lineId=firstRow;lineId<rowsCount;lineId++)   {
        XSSFRow row = sheet.getRow(lineId);
        for (int columnId=firstColumn;columnId<columnsCount;columnId++){
            row.createCell(columnId).setCellValue(object.toString());  }
    }
}

I really do not understand this logic. Firstly, i get row and then I'm trying write the data. I certainly know that, all my data are not null. But compiler says:

Exception in thread "main" java.lang.NullPointerException
    at workhere.WriterXlsx.cleaner(WriterXlsx.java:75)
    at workhere.WriterXlsx.<init>(WriterXlsx.java:19)
    at workhere.Start.main(Start.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

WriterXlsx.java:75 : row.createCell(columnId).setCellValue(object.toString());

I start this method with : cleaner(30,30,"");

3

There are 3 best solutions below

0
On BEST ANSWER

If you just need to clean a row if it exist, why don't check if the row is not null?

Try this:

private void cleaner(Integer columnsCount, Integer rowsCount, Object object){
    XSSFSheet sheet = workBook.getSheetAt(0);
    for (int lineId=0; lineId < rowsCount; lineId++)   {
        XSSFRow row = sheet.getRow(lineId);
        if(row != null)
            for (int columnId=0; columnId < columnsCount; columnId++)
                row.createCell(columnId).setCellValue(object.toString());
    }
}
6
On

Take a look at the API

sheet.getRow(lineId);

returns null if row doesn't exist. You need to create a row before accessing it in case row does not exists (or skip it).

1
On

Answer is : Use Iterator and leave alone the World :) Why @whoAmi isn't right? Because i don't know exist this row or not. Iterator helped me.