网上查了一下,对于这两个版本,有对应的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>