0

我正在尝试从模板加载一个 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);
}

那么可能导致问题的原因是什么?

4

1 回答 1

0

我发现了问题:我在 excel 中打开了模板。因此,一旦我使用模板文件关闭 excel,一切正常 - 不是很奇怪吗?

于 2016-02-29T13:01:49.833 回答