关于用PIO读取Excel2003和2007的不同版本处理

来源:互联网 发布:淘宝小帮手 编辑:程序博客网 时间:2024/06/05 12:37

对于微软2003和2007版本的Excel读取,pio3.7对于2003是有效的,但对于2007版本来说,读取的时候一般会报错。

可以从apache上下载3.8的版本,在处理的过程中,如下工具类:

 public static ArrayList<ArrayList<String>> readExcel(File filePath) {
  
  
  Workbook wb = null;
  try {
       FileInputStream fis = new FileInputStream(filePath);
      wb = new XSSFWorkbook(fis);
      logger.warn("当前Excel版本为2003!");
     return getExcelTable(wb);
  } catch (Exception e) {
      logger.warn("当前Excel版本为2007!");
      try {
            wb = new HSSFWorkbook(new FileInputStream(filePath));
             return getExcelTable(wb);
   } catch (Exception e1) {
          e1.printStackTrace();
           return null;
   }
  }
 }
 
 public static ArrayList<ArrayList<String>> getExcelTable(Workbook wb) {
  ArrayList<ArrayList<String>> table = new ArrayList<ArrayList<String>>();
  Sheet sheet = wb.getSheetAt(0);
  for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
   Row row = sheet.getRow(i);
   if (row != null) {
    ArrayList<String> record = new ArrayList<String>();
    for (int j = 0; j < row.getLastCellNum(); j++) {
     Cell cell = row.getCell((short) j);
     // 判断单元格数据类型,这个地方值得注意:当取某一行中的数据的时候,需要判断数据类型,否则会报错
     // java.lang.NumberFormatException: You cannot get a string value from a numeric cell等等错误
     if (cell.getCellType() == 0) {
      record.add(String.valueOf(Math.round(cell.getNumericCellValue())));
      // System.out.print(i + "/t" + j + "/t" + Math.round(cell.getNumericCellValue())); // 一般的数据类型在excel中读出来都为float型
     } else {
      record.add(cell.getStringCellValue());
     }
    }
    table.add(record);
   }
  }
  return table;
 }

原创粉丝点击