我正在尝试从模板加载一个 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);
}
那么可能导致问题的原因是什么?