上傳Excel同時兼容2003和2007 解決read error和org.apache.poi.poifs.filesystem.OfficeXmlFileException異常

java解析Excel(兼容2003及2007)

剛開始從網上找了個例子使用new HSSFWorkbook(new FileInputStream(excelFile))來讀取Workbook,
對Excel2003以前(包括2003)的版本沒有問題,但讀取Excel2007時發生如下異常:
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)

該錯誤意思是說,文件中的數據是用Office2007+XML保存的,而現在卻調用OLE2 Office文檔處理,應該使用POI不同的部分來處理這些數據,比如使用XSSF來代替HSSF。

String fileName = file.getOriginalFilename();
Workbook hssfWorkbook = null; 
 if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
      workbook = new XSSFWorkbook(file.getInputStream());
 } else {
      workbook = new HSSFWorkbook(file.getInputStream());
 }

List<String> list = new ArrayList<String>();
// 循環工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
    //HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
    Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
    if (hssfSheet == null) {
        continue;
    }
    // 循環行Row
    for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
        //HSSFRow hssfRow = hssfSheet.getRow(rowNum);
        Row hssfRow = hssfSheet.getRow(rowNum);
        if (hssfRow == null) {
            continue;
        }
        //HSSFCell xh = hssfRow.getCell(0);
        Cell xh = hssfRow.getCell(0);
        if (xh == null) {
            continue;
        }
        list.add(xh.getStringCellValue());
    }
}

 

如果只是支持Excel2003的話,需要導入的poi包只需要:
- dom4j-1.6.1.jar
- poi-3.8-20120326.jar
但是如果要同時支持Excel2003和Excel2007就得需要:

dom4j-1.6.1.jar
poi-3.8-20120326.jar
poi-ooxml-3.8-20120326.jar
poi-ooxml-schemas-3.8-20120326.jar
poi-scratchpad-3.8-20120326.jar
xmlbeans-2.3.0.jar
另外,發生如下異常:
java.io.IOException: Read error
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(Unknown Source)
……
是因爲在hssfWorkbook = new HSSFWorkbook(is); 創建失敗拋出異常後FileInputStream被關閉了,所以在創建XSSFWorkbook之前要再重新創建FileInputStream。
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章