poi解析Excel文件版本问题

时间:2023-03-08 16:08:48

poi解析Excel文件时有两种格式: 
HSSFWorkbook格式用来解析Excel2003(xls)的文件 
XSSFWorkbook格式用来解析Excel2007(xlsx)的文件 
如果用HSSFWorkbook解析Excel2007(xlsx)时就会报异常:“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)”

因为HSSFWorkbook和XSSFWorkbook都实现了Workbook接口,所以我们可以用Workbook来解析两个版本的Excel。 
代码如下:

 try{
//将文件的输入流转换成Workbook
Workbook wb = WorkbookFactory.create(numFile.getInputStream());
//获得第一个工作表
Sheet sheet = wb.getSheetAt(0);
//获得第一行
Row row = sheet.getRow(0);
//获得第一行的第一列
Cell cell = row.getCell(0);
}catch (Exception e){
e.printStackTrace();
}