简体   繁体   English

尝试写入已经存在的* .xlsx文件,导致NullPointerException

[英]Trying to write in already existing *.xlsx file causing NullPointerException

following is my function 以下是我的功能

 public static void writeOutputExtraInfo(
        HueIfxModuleMasterStruct<OutputEngineIfxJobMasterStruct> 
    ifxModuleMasterStruct, String filePath)
        throws InvalidFormatException, IOException {
    File file = new File(filePath);
    //XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(file);
    XSSFWorkbook workbook = new XSSFWorkbook(file);
    writeOutputExtraBasicInfo(ifxModuleMasterStruct, workbook);
    FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
    workbook.write(fileOutputStream);
    fileOutputStream.close();
    workbook.close();

}

I get the following error 我收到以下错误

org.apache.poi.POIXMLException: java.lang.NullPointerException
at org.apache.poi.POIXMLDocument.getProperties(POIXMLDocument.java:159) ~[poi-ooxml-3.13.jar:3.13]
at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:210) ~[poi-ooxml-3.13.jar:3.13]

can someone tell whats wrong with the code. 有人能告诉我代码有什么问题吗?

Can you try this way? 你可以这样尝试吗?

Workbook workbook = WorkbookFactory.create(new FileInputStream(filePath));

So, obtaining the Workbook instance from the FileInputStream. 因此,从FileInputStream获得Workbook实例。

There is a comment in the javadoc for the constructor of XSSFWorkbook: XSSFWorkbook的构造函数在javadoc中有一条注释:

Once you have finished working with the Workbook, you should close the package by calling POIXMLDocument.close(), to avoid leaving file handles open. 一旦完成了工作簿的工作,就应该通过调用POIXMLDocument.close()关闭该程序包,以避免打开文件句柄。

So my guess is that the exception is due to the fact that the file is open, not because it exists. 因此,我的猜测是该异常是由于文件已打开而不是因为它存在而造成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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