Total Pageviews

2019/01/12

[Java] [POI] org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML.

Problem
Here has a code snippet to read excel file (.xls file)
    try (InputStream inputStream = new FileInputStream(new File(xlsFile));
        Workbook workbook = new HSSFWorkbook(inputStream);) {

        Sheet sheet = workbook.getSheetAt(0);
        // ignore implementation details

    } catch (IOException e) {
        throw new IOException("讀取 Excel file 發生錯誤", e);
    }

But when I provide xlsx file, it will throw exception:
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)

How-To
If I would like to read xlsx file, the code snippet should be modified as bellow:
    try (InputStream inputStream = new FileInputStream(new File(xlsxFile));
        Workbook workbook = new XSSFWorkbook(inputStream);) {

        Sheet sheet = workbook.getSheetAt(0);
        // ignore implementation details

    } catch (IOException e) {
        throw new IOException("讀取 Excel file 發生錯誤", e);
    }
  


If you don't care about xls or xlsx file, your can modify your code as follows:
    try (Workbook workbook = WorkbookFactory.create(new File(xlsOrXlsxFile));) {
        Sheet sheet = workbook.getSheetAt(0);
        // ignore implementation details
    } catch (IOException e) {
        throw new IOException("讀取 Excel file 發生錯誤", e);
    }


Reference
[1] https://stackoverflow.com/questions/31844308/java-poi-the-supplied-data-appears-to-be-in-the-office-2007-xml

No comments: