我想读取 xls
和 xlsx
文件格式。它对于 xlsx
格式工作正常,但我在上传 xls
文件时遇到以下错误。
代码:
try {
FileInputStream fileInputStream = new FileInputStream("/apps/" + fileName);
//POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
Workbook workBook = WorkbookFactory.create(OPCPackage.open(fileInputStream));
//XSSFWorkbook workBook1 = new XSSFWorkbook();
Sheet ssSheet = workBook.getSheetAt(0);
Iterator rowIterator = ssSheet.rowIterator();
while (rowIterator.hasNext()) {
Row ssRow = (Row) rowIterator.next();
Iterator iterator = ssRow.cellIterator();
List cellTempList = new ArrayList();
while (iterator.hasNext()) {
Cell ssCell = (Cell) iterator.next();
cellTempList.add(ssCell);
}
cellDataList.add(cellTempList);
}
} catch (Exception e) {
e.printStackTrace();
}
错误:
org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:148)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:623)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:230)
请帮忙。
-谢谢
最佳答案
我认为您的问题是由于您尝试使用OPCPackage
构建工作簿,即使您使用WorkbookFactory
。 OPCPackage
“解压缩”您的 .xlsx
以便能够读取其中的 xml 文件,但这不适用于 HSSF,因为它是一个二进制文件。
我的建议是您使用另一个构造函数,例如
WorkbookFactory.create(InputStream 输入)
我想它应该可以正常工作。
关于java - Apache POI xls 文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12110750/