handsomeye

问题描述:在使用poi包进行excel解析时,发现对Excel2003以前(包括2003)的版本没有问题,但读取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)。

原因分析:XSSF不能读取Excel2003以前(包括2003)的版本,如果遇到2007版本的Excel文件就需要在读取前判断文件是2003前的版本还是2007的版本,然后对应调用HSSF或XSSF来读取。

解决方式:目前只能通过后缀名来判断文件版本,代码如下:(如果有高手知道别的解决方法,请告知,谢谢!)

1 public static boolean isExcel2003(String filePath)  
2 {  
3   
4     return filePath.matches("^.+\\.(?i)(xls)$");  
5 
6 }  

获得版本号之后,根据版本号的不同创建不同的对象,代码如下:

 1 /** 根据版本选择创建Workbook的方式 */  
 2   
 3 Workbook wb = null;  
 4   
 5 if (isExcel2003)  
 6 {  
 7    wb = new HSSFWorkbook(inputStream);  
 8 }  
 9 else  
10 {  
11    wb = new XSSFWorkbook(inputStream);  
12 }  

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-11-18
  • 2022-12-23
  • 2021-08-28
  • 2022-12-23
  • 2022-01-12
猜你喜欢
  • 2021-12-23
  • 2021-07-31
  • 2021-12-01
  • 2021-10-20
  • 2022-12-23
  • 2021-07-31
相关资源
相似解决方案