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<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的,这时候如果导入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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值