Total Pageviews

2015/03/20

[Apache POI] 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

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

But as I upload xlsx file, it throw this exception

1
2
3
4
5
6
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)
 at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:131) ~[poi-3.10-FINAL.jar:3.10-FINAL]
 at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104) ~[poi-3.10-FINAL.jar:3.10-FINAL]
 at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:128) ~[poi-3.10-FINAL.jar:3.10-FINAL]
 at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:342) ~[poi-3.10-FINAL.jar:3.10-FINAL]
 at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:323) ~[poi-3.10-FINAL.jar:3.10-FINAL]

Solution
To open an xlsx (Office Open XML) file, you should use XSSFWorkbook instead of HSSFWorkbook, which is used for xls (Excel 97-2003) files.
 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).toString());
    }
} catch (IOException e) {
    throw e;
}


Reference

No comments: