Getting error “Your InputStream was neither an OLE2 stream, nor an OOXML stream” when created file through apache POI

穿精又带淫゛_ 提交于 2019-12-05 23:59:26

Don't create an empty file and try to read it, that won't work. An empty zero byte file is not valid, and can't be loaded Instead, have POI create an new file for you, which you will write later.

Change the code:

if(xlFile.exists() && !xlFile.isDirectory())
    xlFile.delete(); //delete if file already exists.
xlFile.createNewFile();

inStream = new FileInputStream(xlFile);          
workbook =  WorkbookFactory.create(inStream);

To instead be:

if(xlFile.exists() && !xlFile.isDirectory())
    xlFile.delete(); //delete if file already exists.

if (xlFile.toString().endsWith(".xls") {
   workbook = new HSSFWorkbook();
} else {
   workbook = new XSSFWorkbook();
}

Also, if you do want to read an existing file, don't use a stream if you have a file! See this bit of the POI docs for why not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!