1. 程式人生 > >poi 檔案匯入 xls(Excel) 表格

poi 檔案匯入 xls(Excel) 表格

先引入依賴

       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.14</version>
        </dependency>

接著是 controller 層

        /**
	     * 
	     * @param request
	     * @return 匯入ecxel
	     * @throws Exception 
	     */
	    @RequestMapping("/importFT")
	    @ResponseBody
	    public ResponseVO importExcelFT(MultipartFile excelFile, HttpServletRequest request) throws Exception{
	    	  try {
	    		  if(!excelFile.isEmpty()){
		                String fileName = excelFile.getOriginalFilename();
		                
		                System.out.println(fileName);
		                tBusFunctionService.importExcel(fileName, excelFile);
		                return ResponseVO.ok("匯入資料成功");
		            }else{
		            	 return ResponseVO.ok("請選擇檔案");
		            }
		        } catch (Exception e) {
		            e.printStackTrace();
		            return ResponseVO.error("匯入資料失敗");
		        }

	    }

接著是 service 層程式碼(我這裡是將匯入的引入四張表)

    BusSystem querySystemOne(BusSystem entity);//用來poi 匯入查詢 t_bus_system表
	
	void saveSystem(BusSystem entity);// 用來 poi插入 t_bus_system表
	
	BusDomain queryDomain(BusDomain entity);//用來 poi 匯入 查詢 t_bus_domain
	
	void saveDomain(BusDomain entity);//用來  poi 匯入的  插入 t_bus_domain表
	
	void importExcel(String fileName, MultipartFile excelFile) throws Exception;//poi匯入

再接著是serviceImpl 層

1.這個是一個在serviceImpl 層的 方法 用來 獲取對應列的 資料

private String getCellValue(Cell cell) {
		String value = "";
		  if (cell != null) {
		   // 以下是判斷資料的型別
		   switch (cell.getCellType()) {
		   case HSSFCell.CELL_TYPE_NUMERIC: // 數字
		    value = cell.getNumericCellValue() + "";
		    if (HSSFDateUtil.isCellDateFormatted(cell)) {
		     Date date = cell.getDateCellValue();
		     if (date != null) {
		      value = new SimpleDateFormat("yyyy-MM-dd").format(date);
		     } else {
		      value = "";
		     }
		    } else {
		     value = new DecimalFormat("0").format(cell.getNumericCellValue());
		    }
		    break;
		   case HSSFCell.CELL_TYPE_STRING: // 字串
		    value = cell.getStringCellValue();
		    break;
		   case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
		    value = cell.getBooleanCellValue() + "";
		    break;
		   case HSSFCell.CELL_TYPE_FORMULA: // 公式
		    value = cell.getCellFormula() + "";
		    break;
		   case HSSFCell.CELL_TYPE_BLANK: // 空值
		    value = "";
		    break;
		   case HSSFCell.CELL_TYPE_ERROR: // 故障
		    value = "非法字元";
		    break;
		   default:
		    value = "未知型別";
		    break;
		   }
		  }
		  return value.trim();
	}

 2.poi 匯入的 serviceImpl 的實現 

@Override
	public void importExcel(String fileName, MultipartFile excelFile) throws Exception {
		// TODO Auto-generated method stub
		 //  1、用HSSFWorkbook開啟或者建立“Excel檔案物件”
		  //
		  //  2、用HSSFWorkbook物件返回或者建立Sheet物件
		  //
		  //  3、用Sheet物件返回行物件,用行物件得到Cell物件
		  //
		  //  4、對Cell物件讀寫。
		  //獲得檔名 
          // getCellValue(row.getCell(i)) 這裡是獲取i列所對應的資料 
		
		Workbook workbook = null ;
		  if(fileName.endsWith(XLS)){ 
		   //2003 
		   workbook = new HSSFWorkbook(excelFile.getInputStream()); 
		  }else if(fileName.endsWith(XLSX)){ 
		   //2007 
		   workbook = new XSSFWorkbook(excelFile.getInputStream()); 
		  }else{
		   throw new Exception("檔案不是Excel檔案");
		  }
		  Sheet sheet = workbook.getSheet("Sheet1");
		  int rows = sheet.getLastRowNum();// 指的行數,一共有多少行+
		  if(rows==0){
		   throw new Exception("請填寫資料");
		  }
		  
		  
		  for (int i = 1; i <= rows+1; i++) {
			   // 讀取左上端單元格
			   Row row = sheet.getRow(i);
			   // 行不為空
			   if (row != null) {//邏輯儲存程式碼 呼叫相應的 dao層進行儲存
				   
				   //先判斷 function 中有沒有 name等於匯入的名字 
				   BusFunction busFunction = new BusFunction();
				   busFunction.setName(getCellValue(row.getCell(3)));
				   
				   if(!busFunction.getName().equals("")) {
					   
						   
					   
					   
					   BusFunction querybusFunction = queryOne(busFunction);
					   if(querybusFunction==null) {//沒有 直接匯入 function 和 table
						   String busFunctionId = Uuid.getUUid();
						   
						   //插入到 t_bus_function 表中
						   busFunction.setId(busFunctionId);
						   busFunction.setDesc(getCellValue(row.getCell(4)));
						   BusSystem busSystem = new BusSystem();//查詢 systemId
						   busSystem.setName(getCellValue(row.getCell(1)));
						   BusSystem queryBusSystem = querySystemOne(busSystem);
						   busFunction.setSystemId(queryBusSystem.getSystemId());
						   save(busFunction);//插入到 t_bus_function 表中
						   
						   //把資料新增 到 busTable中
						   BusTable busTable= new BusTable();
						   busTable.setCode(getCellValue(row.getCell(5)));
						   if(busTable.getCode()!=null||!busTable.getCode().equals("")) {
							   
							   busTable.setId(Uuid.getUUid());
							   busTable.setName(getCellValue(row.getCell(6)));
							   busTable.setDesc(getCellValue(row.getCell(7)));
							   busTable.setFunId(busFunctionId);//把資料儲存到 t_bus_table中
							   tbusTableDao.save(busTable);
							   
							   
						   }
						   
					   }else {//如果有 在查詢 table中的英文名稱有沒有和匯入一樣的  有就跳過 沒有直接匯入
						   BusTable bt= new BusTable();
						   bt.setCode(getCellValue(row.getCell(5)));
						   if(!bt.getCode().equals("")||bt.getCode()!=null) {
							   BusTable queryBusTable = tbusTableDao.queryOne(bt);//先查詢 t_bus_table 中是否有相同名稱的 
							   if(queryBusTable==null) {//沒有相同名稱的 插入  有相同的 直接跳過
								   BusTable bustable= new BusTable();
								   bustable.setId(Uuid.getUUid());
								   bustable.setName(getCellValue(row.getCell(6)));
								   bustable.setCode(getCellValue(row.getCell(5)));
								   bustable.setDesc(getCellValue(row.getCell(7)));
								   bustable.setFunId(querybusFunction.getId());
								   tbusTableDao.save(bustable);
							   }
						   }
						   
					   }
				   }
				   
				
			   }
			  }
		
		
		
	}