1. 程式人生 > >java使用POI讀取excel檔案,相容xls和xlsx

java使用POI讀取excel檔案,相容xls和xlsx

public List<Double> readExcels(InputStream is)throws Exception{
List<Double> xlsxList = new ArrayList<Double>();
    try {
             if(is ==null){
                   throw new IOException("檔案不正確!"); 
              }
            Workbook workbook = WorkbookFactory.create(is);
            FormulaEvaluator fe = workbook.getCreationHelper().createFormulaEvaluator();
            //獲取第一張表
            Sheet sheet = workbook.getSheetAt(0);
            if(sheet == null){
                  throw new IOException("傳入的excel的第一張表為空!"); 
             }
            for(int rowNum = 0;rowNum <= sheet.getLastRowNum(); rowNum++){
                  Row row = sheet.getRow(rowNum);
                  if(row != null){
                       //獲得當前行的開始列  
                       int firstCellNum = row.getFirstCellNum();  
                      //獲得當前行的列數  
                      int lastCellNum = row.getPhysicalNumberOfCells();  
                      String result = "";
                      //迴圈當前行  
                      for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
                           Cell cell = row.getCell(cellNum);  
                           double value = 0;
                          if(null!=fe.evaluate(cell)){
                               value = fe.evaluate(cell).getNumberValue();
                           }
                          result = result + cellNum + ":"+value + "----";
                       }  
                      System.out.println("result---"+result);
                  }
            }
            is.close();
    } catch (FileNotFoundException e) {
         throw new Exception("檔案不正確!");
    }
      return xlsxList;
}

   public static void main(String[] args) throws Exception {  
        InputStream is = new FileInputStream("D:\\test.xlsx");
        ReadExcel re = new ReadExcel();
       re.readExcels(is);
    }
}