Search code examples
javaapache-poixls

Apache POI xls file error


I want to read both xls and xlsx file format. It is working fine for xlsx format but I am getting following error while uploading xls file.

Code:

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();
}

Error:

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)

Please help.

-Thanks


Solution

  • I think that your problem is due to you trying to construct your workbook with the OPCPackage, even if you use WorkbookFactory. OPCPackage "unzip" your .xlsx in order to be able to read the xml files inside, but this should not work for HSSF since it is a binary file.

    My recomendation would be that you use another constructor such as

    WorkbookFactory.create(InputStream input)

    I guess it should work fine.