我正在尝试从模板加载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:
调用@Test
public void someTest() throws IOException {
WorkDiaryExcel to = new WorkDiaryExcel(reportMock);
FileOutputStream out = new FileOutputStream("out.xls");
to.write(out);
}
那么什么可能导致问题?
答案 0 :(得分:0)
我发现了问题:我在excel中打开了模板。因此,只要我使用模板文件关闭excel一切正常 - 非常奇怪不是吗?