1. 程式人生 > >excel檔案匯入(xls,xlsx)

excel檔案匯入(xls,xlsx)

public class ExcelSwitchMap {
 /***
  *
  * @param in   POIFSFileSystem
  * @param max  所匯入excel的列數
  * @return map
  * @throws IOException
  */
 @SuppressWarnings({ "deprecation", "resource" })
 public static Map<Integer, Map<Integer, List<String>>> getExcel(POIFSFileSystem in,int max)
   throws IOException {
  Map<Integer, Map<Integer, List<String>>> map = new HashMap<Integer, Map<Integer, List<String>>>();// 總map
  Map<Integer, List<String>> sheetMap = null;// 每個sheet的map
  List<String> list = null;// 每行一個list
  HSSFWorkbook workBook = null;
  try {
   workBook = new HSSFWorkbook(in);
  } catch (final Exception e) {
   throw new IOException("讀取上傳檔案失敗");
  }
  /**
   * 獲得Excel中工作表個數
   */
  // sheet.autoSizeColumn(( short ) 0 );//匯出自動適應寬度
  int sheetSize = workBook.getNumberOfSheets();
//  System.out.println("工作表個數 :" + sheetSize);
  for (int i = 0; i < sheetSize; i++) {
   sheetMap = new HashMap<Integer, List<String>>();
//   System.out.println("工作表名稱:" + workBook.getSheetName(i));
   HSSFSheet sheet = workBook.getSheetAt(i);
   int rows = sheet.getPhysicalNumberOfRows(); // 獲得行數
   if (rows > 0) {
    for (int j = 0; j < rows; j++) { // 行迴圈
     list = new ArrayList<String>();
     HSSFRow row = sheet.getRow(j);
     if (row != null) {
      int cells = row.getLastCellNum();// 獲得列數
      if(cells<max){
       cells = max;
      }
      for (short k = 0; k < cells; k++) { // 列迴圈
       HSSFCell cell = row.getCell(k);
       String value = "";
       if(cell != null){
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_NUMERIC: // 數值型
         if (HSSFDateUtil.isCellDateFormatted(cell)) {
          // 如果是date型別則 ,獲取該cell的date值
          value = HSSFDateUtil.getJavaDate(
            cell.getNumericCellValue())
            .toString();
         } else {// 純數字
          value = String.valueOf(cell
            .getNumericCellValue());
         }
         if(value.matches("^((\\d+\\.?\\d+)[Ee]{1}(\\d+)){1}")){
          DecimalFormat df = new DecimalFormat("#.##");
          value = df.format(Double.parseDouble(value));
         }
         break;
        case HSSFCell.CELL_TYPE_STRING: // 字串型
         value = cell.getRichStringCellValue()
           .toString().trim();
         break;
        case HSSFCell.CELL_TYPE_FORMULA:// 公式型
         // 讀公式計算值
         value = String.valueOf(cell
           .getNumericCellValue());
         if (value.equals("NaN")) {// 如果獲取的資料值為非法值,則轉換為獲取字串
          value = cell.getRichStringCellValue()
            .toString();
         }
         break;
        case HSSFCell.CELL_TYPE_BOOLEAN:// 布林
         value = "" + cell.getBooleanCellValue();
         break;
        /* 此行表示該單元格值為空 */
        case HSSFCell.CELL_TYPE_BLANK: // 空值
         value = "";
         break;
        case HSSFCell.CELL_TYPE_ERROR: // 故障
         value = "";
         break;
        default:
         value = cell.getRichStringCellValue()
           .toString().trim();
        }
       }
       list.add(value);
      }
      if(!isAllNull(list)){
       sheetMap.put(j, list);
      }
     }
    }
   }
   map.put(i, sheetMap);
  }
  return map;
 }
 /**
  * 如果list裡面的值全為空 則範圍true 反之則為false
  * @param l list
  * @return
  */
 private static boolean isAllNull(List<String> l){
  int i=0;
  for(String s : l){
   if(!"".equals(s)){
    i++;
   }
  }
  if(i>0){
   return false;
  }
  return true;
 }
 
 public static void main(String[] args) {
  String filePath = "d:/template.xls";
  try {
   POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));
   Map<Integer, Map<Integer, List<String>>> map = getExcel(fs,9);
   for(Entry<Integer, List<String>> ent : map.get(0).entrySet()){
    System.out.println(ent);
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}