Total Pageviews

2015/03/20

[Apache POI] HSSFWorkbook and XSSFWorkbook

According to the two posts....
http://albert-myptc.blogspot.tw/2015/03/orgapachepoipoifsfilesystemofficexmlfil.html
http://albert-myptc.blogspot.tw/2015/03/invalidformatexception-package-should.html

If you would like to read xls file, you should utilize HSSFWorkbook. If you misuse it, i.e. upload 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)

If you would like to read xlsx file, you should utilize XSSFWorkbook. If you misuse it, i.e. upload xls file, it will throw exception : 
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]


Hence, if I would like to accept the both, here is my code snippet
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
try {
    // file extension validation
    String extension = StringUtils.upperCase(FilenameUtils.getExtension(fileName));
    if (!("XLS".equals(extension)) && !("XLSX".equals(extension))) {
        String errorMsg = "只接受副檔名為xls與xlsx的檔案, fileName = " + fileName;
        throw new RuntimeException(errorMsg);
    }

    Workbook workbook = null;
    Sheet sheet = null;

    if ("XLS".equals(extension)) {
        // Get the workbook instance for XLS file
        workbook = new HSSFWorkbook(inputStream);
    } else if ("XLSX".equals(extension)) {
        // Get the workbook instance for XLSX file
        workbook = new XSSFWorkbook(inputStream);
    }

    // Get the specific sheet from the workbook
    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;
}




No comments: