一、异常描述
通过poi解析excel的xls格式文件报出“Exception in thread "main" org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]”,日志如下
Exception in thread "main" org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]@b@ at org.apache.poi.util.PackageHelper.open(PackageHelper.java:41)@b@ at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:204)@b@ at xwood.tools.ExcelReaderTest$ExcelReader.parseExcel(ExcelReaderTest.java:69)@b@ at xwood.tools.ExcelReaderTest$ExcelReader.getDatas(ExcelReaderTest.java:118)@b@ at xwood.tools.ExcelReaderTest.main(ExcelReaderTest.java:129)@b@Caused by: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]@b@ at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:178)@b@ at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:662)@b@ at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:269)@b@ at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)@b@ ... 4 more
二、解决方法
该异常是由于解析excel后缀为xls、xlsx格式时本应该分别HSSFWorkbook、XSSFWorkbook初始化流格式化,这边误用XSSFWorkbook来初始化xls后缀格式文件,关于详细的解析代码示例可参考“通过apache的poi读取excel数据的完整源码示例”文章(包含依赖包和源码)