读excel文件踩坑--格式

遇到上传excel文件程序异常,查看日志发现
异常信息:org.apache.poi.openxml4j.exceptions.OLE2NotOfficeXmlFileException: The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF) : The supplied data appears to be in the OLE2 Format. You are calling the part of POI that deals with OOXML (Office Open XML) Documents. You need to call a different part of POI to process this data (eg HSSF instead of XSSF)
org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:172)
org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:229)
org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:97)
org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:342)
org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
org.apache.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:285)

这部分是原有功能,并未做修改,结合百度查询结果
猜测是兼容性问题或excel文件本身有问题(比如:头信息不正确)。
根据前人类似的经验,将该xls文件另存为xlsx格式。
再次上传,正常。

因此确定是兼容性问题,根据报错信息的提示
【You need to call a different part of POI to process this data (eg HSSF instead of XSSF)】
查看代码发现,之前使用public XSSFWorkbook(InputStream is)这个构造器来读取excel文件
将其替换为HSSFWorkbook。

发现上传xls正常,上传xlsx出现异常
异常信息:org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF) : The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:152)
org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:140)
org.apache.poi.poifs.filesystem.NPOIFSFileSystem.(NPOIFSFileSystem.java:302)
org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:398)
org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:379)

测试后得出结论XSSFWorkbook支持xlsx | HSSFWorkbook支持xls
根据文件类型选择合适的类,完成兼容。

以上

你可能感兴趣的:(读excel文件踩坑--格式)