Total Pageviews

2015/03/20

[Apache POI] InvalidFormatException: Package should contain a content type part [M1.13]

Problem
I have a file upload function, which accept xlsx and xls file.


Here is the code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
try {
    // Get the workbook instance for excel file
    Workbook xslxBook = new XSSFWorkbook(inputStream);
    // Get the specific sheet from the workbook
    Sheet sheet = xslxBook.getSheetAt(0);
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        log.debug("row = " + row.getCell(0));
    }
} catch (IOException e) {
    throw e;
}


But as I upload xls file, it throw this exception
1
2
3
 org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
  at org.apache.poi.util.PackageHelper.open(PackageHelper.java:41) ~[poi-ooxml-3.9.jar:3.9]
  at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:204) ~[poi-ooxml-3.9.jar:3.9]

Solution
The error is telling you that POI couldn't find a core part of the OOXML file. Your file isn't a valid OOXML file, let alone a valid .xlsx file.  So you need to use HSSFWorkbook instead of XSSFWorkbook.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
try {
     // Get the workbook instance for XLS file
     Workbook workbook = new HSSFWorkbook(inputStream);
     // Get the specific sheet from the workbook
     Sheet sheet = workbook.getSheetAt(0);
     Iterator<Row> rowIterator = sheet.iterator();
     while (rowIterator.hasNext()) {
         Row row = rowIterator.next();
         log.debug("row = " + row.getCell(0));
     }
 } catch (IOException e) {
     throw e;
 }



Reference
[1] http://stackoverflow.com/questions/6758364/getting-exceptionorg-apache-poi-openxml4j-exception-no-content-type-m1-13

1 comment:

Unknown said...

Did this solve your problem? I'm facing a similar issue, for me i'm reading the same file and i have to append my data in the end.
And it has worked many days and suddenly this problem happened , i don't get it