Java解析Excel文档,2003和2007版本不兼容问题

网上查了一下,对于这两个版本,有对应的api,稍不注意就会报:

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)


好在他们都是实现Workbook接口,因此根据网上的资料,总结及解决代码如下:

        //根据不同的版本创建不同的对象
        Workbook sheets = null;
        if (WBUtil.isExcel2003(xlsxPath)) {
            sheets = new HSSFWorkbook(new FileInputStream(xlsxFile));
        } else {
            sheets = new XSSFWorkbook(new FileInputStream(xlsxFile));
        }
public final class WBUtil {

    // @描述:是否是2003的excel,返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    //@描述:是否是2007的excel,返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}

依赖:

        <!--xlsx解析-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
        </dependency>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值