Java上传Excel同时兼容2003和2007 解决read error和org.apache.poi.poifs.filesystem.OfficeXmlFileException异常

上传Excel部分代码块:

FileInputStream is = new FileInputStream(file);
//HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); 
Workbook hssfWorkbook = null; 
try { 
    hssfWorkbook = new HSSFWorkbook(is); 
} catch (Exception ex) {
    // 解决read error异常
    is = new FileInputStream(file);
    hssfWorkbook = new XSSFWorkbook(is); 
} 
//HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
List list = new ArrayList();
// 循环工作表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的,这时候如果导入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)

如果只是支持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。

参考文章:
1.http://my.oschina.net/u/658145/blog/268112
2.http://blog.csdn.net/mmm333zzz/article/details/7962377
3.http://blog.csdn.net/sdfe63/article/details/20955209

你可能感兴趣的:(技术)