简体   繁体   中英

NullPointerException on writing excel file with apache poi

I am trying to load an excel file (xls) from template, set one cell's value and write it to another file. But i get this exception:

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)
    ...

(by the way a really bad message ;-))

here is the code:

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

}

This code is called from test:

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

So what could cause the problem?

I found the problem: I left the template open in excel. So as soon as i closed excel with the template file all worked fine - very odd isn't it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM