Search code examples
javaapache-poixssf

XSSF. NullPointerException


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


Solution

  • 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());
        }
    }