1. 程式人生 > >poi匯入excel,支援xls和xlsx格式

poi匯入excel,支援xls和xlsx格式

public static void checkFile(MultipartFile file) throws IOException{
   //判斷檔案是否存在
   if(null == file){

      throw new AudaqueException("檔案不存在!");
   }
   //獲得檔名
   String fileName = file.getOriginalFilename();
   //判斷檔案是否是excel檔案
   if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){

      throw new AudaqueException(fileName + "不是excel檔案");
   }
}
public static Workbook getWorkBook(MultipartFile file) {
   //獲得檔名
   String fileName = file.getOriginalFilename();
   //建立Workbook工作薄物件,表示整個excel
   Workbook workbook = null;
   try {
      //獲取excel檔案的io流
      InputStream is = file.getInputStream();
      //根據檔案字尾名不同(xls和xlsx)獲得不同的Workbook實現類物件
      if(fileName.endsWith(xls)){
         //2003
         workbook = new HSSFWorkbook(is);
      }else if(fileName.endsWith(xlsx)){
         //2007
         workbook = new XSSFWorkbook(is);
      }
   } catch (IOException e) {
      log.info(e.getMessage());
   }
   return workbook;
}
public static String getCellValue(Cell cell){
   String cellValue = "";
   if(cell == null){
      return cellValue;
   }
   //把數字當成String來讀,避免出現1讀成1.0的情況
   if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
      cell.setCellType(Cell.CELL_TYPE_STRING);
   }
   //判斷資料的型別
   switch (cell.getCellType()){
      case Cell.CELL_TYPE_NUMERIC: //數字
         cellValue = String.valueOf(cell.getNumericCellValue());
         break;
      case Cell.CELL_TYPE_STRING: //字串
         cellValue = String.valueOf(cell.getStringCellValue());
         break;
      case Cell.CELL_TYPE_BOOLEAN: //Boolean
         cellValue = String.valueOf(cell.getBooleanCellValue());
         break;
      case Cell.CELL_TYPE_FORMULA: //公式
         cellValue = String.valueOf(cell.getCellFormula());
         break;
      case Cell.CELL_TYPE_BLANK: //空值
         cellValue = "";
         break;
      case Cell.CELL_TYPE_ERROR: //故障
         cellValue = "非法字元";
         break;
      default:
         cellValue = "未知型別";
         break;
   }
   return cellValue;
}

/**
 * 讀入excel檔案,解析後返回
 * @param file
 * @throws IOException
 */
public  List<AdqmMetadata>  readExcel(MultipartFile file,List<AdqmMetadata> dataList) throws IOException, AudaqueException{
   //檢查檔案
   checkFile(file);
   //獲得Workbook工作薄物件
   Workbook workbook = getWorkBook(file);
   //dataList 建立返回物件,把每行中的值作為一個物件,所有行作為一個集合返回
   if(workbook != null){
      for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
         String sheetName = workbook.getSheetAt(sheetNum).getSheetName();
         // 根據name判斷sheet型別
         if (sheetName.startsWith("程式碼清單")) {

         Sheet sheet = workbook.getSheetAt(sheetNum);
         if(sheet == null){
            continue;
         }
         //獲得當前sheet的開始行
         int firstRowNum  = sheet.getFirstRowNum();
         //獲得當前sheet的結束行
         int lastRowNum = sheet.getLastRowNum();
         //迴圈除了第一行的所有行
            // 程式碼集資料
            // 獲取列標題
            Row row0 = sheet.getRow(firstRowNum);
            // 如果列名不對 終止匯入  暴露錯誤
            for(int cellNum = 0; cellNum < 5;cellNum++){
               Cell cell = row0.getCell(cellNum);
               if (!"程式碼集編碼".equals(getCellValue(cell))&&cellNum==0) {
                  throw new AudaqueException(sheetName + "表單第1列標題模板錯誤");
               }else
               if (!"標準編號".equals(getCellValue(cell))&&cellNum==1) {
                  throw new AudaqueException(sheetName + "表單第2列標題模板錯誤");
               }else
               if (!"程式碼集名稱".equals(getCellValue(cell))&&cellNum==2) {
                  throw new AudaqueException(sheetName + "表單第3列標題模板錯誤");
               }else
               if (!"標準型別".equals(getCellValue(cell))&&cellNum==3) {
                  throw new AudaqueException(sheetName + "表單第4列標題模板錯誤");
               }else
               if (!"標準程式碼".equals(getCellValue(cell))&&cellNum==4) {
                  throw new AudaqueException(sheetName + "表單第5列標題模板錯誤");
               }else
               if (!"程式碼名稱".equals(getCellValue(cell))&&cellNum==5) {
                  throw new AudaqueException(sheetName + "表單第6列標題模板錯誤");
               }

            }

         for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
            //獲得當前行
            Row row = sheet.getRow(rowNum);
            if(row == null){
               continue;
            }

            if (row != null ){
               //獲得當前行的開始列
               int firstCellNum = row.getFirstCellNum();
               //獲得當前行的列數
               int lastCellNum = row.getPhysicalNumberOfCells();
               String[] cells = new String[row.getPhysicalNumberOfCells()];
               //迴圈當前行
               AdqmMetadata adqmMetadata = new AdqmMetadata();
               for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
                  Cell cell = row.getCell(cellNum);
                  //程式碼集編碼
                  String valus=getCellValue(cell);
                  if (cellNum==0){
                     if (StringUtils.isNotBlank(valus)){
                        adqmMetadata.setCodesetCode(valus);
                     }else{
                        throw new AudaqueException(sheetName + "表單第"+rowNum+1+"行第1列程式碼集編碼內容不能為空!");
                     }
                  }else if (cellNum==1){
                     // 程式碼集描述
                     adqmMetadata.setValusDesc(valus);
                  }else if (cellNum==2){
                     // 程式碼集描述
                     if (StringUtils.isNotBlank(valus)){
                        adqmMetadata.setRemarks(valus);
                     }else{
                        throw new AudaqueException(sheetName + "表單第"+rowNum+1+"行第3列程式碼集名稱內容不能為空!");
                     }
                  }else if (cellNum==3){
                                  // 標準型別
                     if (StringUtils.isNotBlank(valus)){
                        DateTypeCodeEnum dateTypeCodeEnum=DateTypeCodeEnum.getEnumByValuesName(valus);
                        if (dateTypeCodeEnum!=null){
                           adqmMetadata.setDataType(dateTypeCodeEnum.getValue());
                        }else{
                           throw new AudaqueException(sheetName + "表單第"+rowNum+1+"行第4列的標準型別不是標準型別");
                        }
                     }else{
                        throw new AudaqueException(sheetName + "表單第"+rowNum+1+"行第4列標準型別內容為空");
                     }
                  }else if (cellNum==4){
                     // 程式碼
                     if (StringUtils.isNotBlank(valus)){
                        adqmMetadata.setMetadataCode(valus);
                     }else{
                        throw new AudaqueException(sheetName + "表單第"+rowNum+1+"行第5列標準程式碼內容不能為空!");
                     }
                  }else if (cellNum==5){
                     // 名稱
                     if (StringUtils.isNotBlank(valus)){
                        adqmMetadata.setMetadataName(valus);
                     }else{
                        throw new AudaqueException(sheetName + "表單第"+rowNum+1+"行第6列程式碼名稱內容不能為空!");
                     }
                  }

               }
                      // 新增到集合中
               adqmMetadata.setCreateUser(getUserId());
               adqmMetadata.setCreateTime(new Date());
               dataList.add(adqmMetadata);


            }else{


            }

         }
      }
      workbook.close();
   }

}
   return dataList;
}


@RequestMapping(value = "importAdqmMetadataExcel1.do")
@ResourcePermissions(name = "批量匯入",value = "importAdqmMetadataExcel1")
@ResponseBody
public Map<String,Object> importAdqmMetadataExcel1(HttpServletRequest request, HttpServletResponse response)throws IOException, AudaqueException {
   Map<String,Object> result = new HashMap<String, Object>();
   int effectives = 0;
   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
   Map<String, MultipartFile> files = multipartRequest.getFileMap();
   List<AdqmMetadata> dataList = new ArrayList<AdqmMetadata>();
   for(Map.Entry<String, MultipartFile> entry :files.entrySet()) {
      MultipartFile file = entry.getValue();
      //檢查檔案
      dataList=readExcel(file,dataList);
   }
   if (dataList!=null&&dataList.size()>0){
      adqmMetadataService.batchInsertAdqmMetadataSelective(dataList);
      result.put("effectives", dataList.size());
   }else{
      result.put("effectives", effectives);
   }
   return result;
}