使用 apache poi 写入 excel 文件时出现 NullPointerException

NullPointerException on writing excel file with apache poi

我正在尝试从模板加载 excel 文件 (xls),设置一个单元格的值并将其写入另一个文件。但我得到这个例外:

java.lang.NullPointerException
    at org.apache.poi.poifs.filesystem.FilteringDirectoryNode$FilteringIterator.<init>(FilteringDirectoryNode.java:193)
    at org.apache.poi.poifs.filesystem.FilteringDirectoryNode$FilteringIterator.<init>(FilteringDirectoryNode.java:188)
    at org.apache.poi.poifs.filesystem.FilteringDirectoryNode.getEntries(FilteringDirectoryNode.java:101)
    at org.apache.poi.poifs.filesystem.FilteringDirectoryNode.iterator(FilteringDirectoryNode.java:105)
    at org.apache.poi.poifs.filesystem.EntryUtils.copyNodes(EntryUtils.java:74)
    at org.apache.poi.poifs.filesystem.EntryUtils.copyNodes(EntryUtils.java:90)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.write(HSSFWorkbook.java:1395)
    at de.ajs.dailyreport.runtime.services.WorkDiaryExcel.write(WorkDiaryExcel.java:37)
    at de.ajs.dailyreport.runtime.services.WorkDiaryExcelTest.someTest(WorkDiaryExcelTest.java:35)
    ...

(顺便说一句,这是一条非常糟糕的消息 ;-))

代码如下:

public class WorkDiaryExcel {

    private final Report report;

    /**
     * row, cell for date
     */
    private static final int[] DATE_FIELD = new int[] { 7, 7 };
    private HSSFWorkbook excel;

    public WorkDiaryExcel(Report report) {
        this.report = report;
        try(HSSFWorkbook excel = new HSSFWorkbook(WorkDiaryExcel.class.getResourceAsStream("/template.xls"))) {
            this.excel = excel;
            HSSFSheet sheet = excel.getSheetAt(0);
            sheet.getRow(DATE_FIELD[0]).getCell(DATE_FIELD[1]).setCellValue(report.getDate());
        } catch (IOException e) {
            throw new IllegalStateException("Problem on loading excel from template: ", e);
        }

    }

    public void write(OutputStream out){
        try {
            excel.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new IllegalArgumentException("Problem on writing excel to output stream: ", e);
        }
    }

}

此代码是从测试中调用的:

@Test
public void someTest() throws IOException {
    WorkDiaryExcel to = new WorkDiaryExcel(reportMock);
    FileOutputStream out = new FileOutputStream("out.xls");
    to.write(out);
}

那么是什么导致了这个问题?

我发现了问题:我在 excel 中让模板处于打开状态。因此,一旦我使用模板文件关闭 excel,所有工作都正常 - 很奇怪不是吗?