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

我真的不明白这个逻辑。首先,我得到行,然后我正在尝试写入数据。我当然知道,我所有的数据都不为空。但是编译器说:

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

我开始这个方法:cleaner(30,30,"");

4

3 回答 3

3

看看API

sheet.getRow(lineId);

如果行不存在,则返回 null。如果行不存在(或跳过它),您需要在访问它之前创建一行。

于 2013-09-03T07:43:16.550 回答
2

如果您只需要清除一行(如果存在),为什么不检查该行是否不为空?

试试这个:

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());
    }
}
于 2013-09-03T08:14:16.130 回答
0

答案是:使用Iterator并离开世界 :) 为什么@whoAmi 不对?因为我不知道是否存在这一行。Iterator帮助过我。

于 2013-09-03T08:04:33.703 回答