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。
代码如下:
1 try{ 2 //将文件的输入流转换成Workbook 3 Workbook wb = WorkbookFactory.create(numFile.getInputStream()); 4 //获得第一个工作表 5 Sheet sheet = wb.getSheetAt(0); 6 //获得第一行 7 Row row = sheet.getRow(0); 8 //获得第一行的第一列 9 Cell cell = row.getCell(0); 10 }catch (Exception e){ 11 e.printStackTrace(); 12 }