异常描述
Workbook读取excel,由于excel分为2003和2007,版本不匹配时,会出现如下异常:
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)
或者:
org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file: '*.xls'
处理方法
所以在解析时,需要分别用HSSFWorkbook、XSSFWorkbook处理。
代码可以如下:
Workbook book = null;
try {
book = new XSSFWorkbook(excelFile);
} catch (Exception ex) {
book = new HSSFWorkbook(new FileInputStream(excelFile));
}