環境:
JDK 1.8,springboot 2.0 ,mybaties plus, layui
本文兩個點,一個是導出模板給用戶,一個是用戶上傳的文件導入到數據庫中,使用的是POI
我們先引入poi的依賴
<!-- excel導入 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.9</version> </dependency> <!-- excel結束 -->
一, 導出模板
前端代碼, 我這裏使用的是阿里雲
1.下載模板的按鈕HTML代碼
<button type="button" class="layui-btn" @click="download"> 下載模板 </button>
2.js代碼
download: function(){ window.open(baseURL + "oagoal/downloadExcel"); },
3.controller
@RequestMapping(value = "/downloadExcel",method = RequestMethod.GET) public void download(HttpServletResponse res) { //定義文件名 String fileName = "oagoal.xls"; //設置響應頭 res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buff = new byte[1024]; //高效輸入流 BufferedInputStream bis = null; //輸出流 OutputStream os = null; try { //獲得輸出流 os = res.getOutputStream(); File path = null; //文件位置 path = new File(ResourceUtils.getURL("classpath:").getPath()); bis = new BufferedInputStream(new FileInputStream(new File(path.getAbsolutePath(),"statics/doc/" + fileName))); int i = bis.read(buff); while(i != -1){ os.write(buff,0,buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { try { if(bis != null){ bis.close(); } } catch (IOException e) { e.printStackTrace(); } } }
模板是放在項目裏的目錄裏的,這個是簡單的輸出流,下載模板
一, 上傳Excel文件導入到數據庫
1.按鈕的html代碼
<button type="button" class="layui-btn" id="test1"> <i class="layui-icon"></i>批量上傳 </button>
2.上傳的js代碼
layui.use('upload', function() { var upload = layui.upload; //執行實例 var uploadInst2 = upload.render({ elem: '#test1' //綁定元素 ,url: baseURL + 'oagoal/uploadExcel' //上傳接口 ,accept: 'file' ,before: function(obj){ layer.load(); //上傳loading } ,done: function(res){ //上傳完畢回調 if (res.code == 0) { layer.msg('操作成功', { icon: 1, time: 1000 }, function() { layer.closeAll('loading'); //關閉loading vm.reload(); closeRight(); }); } else { layer.msg(res.msg, { time: 1000 }); } } ,error: function(){ //請求異常回調 layer.closeAll('loading'); //關閉loading // 請求異常回調 layer.msg('上傳失敗', { time: 1000 }); } }); });
3.controller層
@RequestMapping("/uploadExcel") public R upload(@RequestParam MultipartFile file) throws Exception { if(file.isEmpty()){ throw new RRException("上傳文件不能爲空"); } //文件後綴 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //文件名和大小 String name = file.getOriginalFilename(); Long size = file.getSize(); if(name == null || ("").equals(name) && size == 0 ){ throw new ApplicationException("上傳文件不能爲空"); } boolean b = oaGoalService.batchImport(name, file); R r ; if(b){ r = R.ok(); }else{ r = R.error("批量導入錯誤"); } return r; }
3.service代碼
/* * @Author YL * @Description //TODO controller調用的入口 * @Date 23:05 2018/8/16 * @Param name 文件名 * @return **/ @Override @Transactional public boolean batchImport(String name, MultipartFile file) { List<OaGoalEntity> goalList = this.getListByEcxel(name, file); if(goalList.size() > 0 && goalList != null){ this.insertBatch(goalList); return true; } return false; } public List<OaGoalEntity> getListByEcxel(String name,MultipartFile file){ List<OaGoalEntity> goalList = new ArrayList<>(); //輸入流 InputStream buffIn = null; if(validName(name)){ //默認認爲是2003 boolean isExcel2003 = true; if(this.isExcel2007(name)){ //是2007版本 isExcel2003 = false; } try { //獲得輸入流 buffIn = file.getInputStream(); Workbook wb = null; if(isExcel2003){ wb = new HSSFWorkbook(buffIn); }else{ wb = new XSSFWorkbook(buffIn); } goalList = this.getExcelByWorkBook(wb); } catch (IOException e) { e.printStackTrace(); } finally { } } return goalList; } /* * @Author YL * @Description //TODO 從流讀取數據 * @Date 23:05 2018/8/16 * @Param * @return **/ public List<OaGoalEntity> getExcelByWorkBook(Workbook wb){ List<OaGoalEntity> goalList = null; //獲得第一個sheet Sheet sheet = wb.getSheetAt(0); //得到Excel的行數 Integer totalRows = sheet.getPhysicalNumberOfRows(); //判斷是否有行數 Integer totalCells = 0; List<SysConfigEntity> listByOagoalType = sysConfigService.queryKeyOrValue("cf_goal_type"); List<SysConfigEntity> listByOagoalChargeType = sysConfigService.queryKeyOrValue("cf_goal_charge_type"); if(totalRows > 0 && sheet.getRow(0) != null){ //得到列數 totalCells = sheet.getRow(0).getPhysicalNumberOfCells(); } SysUserEntity userEntity = ShiroUtils.getUserEntity(); Long empId = userEntity.getEmpId(); goalList = new ArrayList<OaGoalEntity>(); OaGoalEntity oaGoalEntity = null; SysDeptEntity dept = null; SysDeptEntity createDept = null; //循環取值 for(int r = 1;r < totalRows;r++){ //獲得當前這一行 Row row = sheet.getRow(r); if(row == null){ //如果爲空跳出本次循環 continue; } oaGoalEntity = new OaGoalEntity(); //循環列 for(int c = 0;c < totalCells;c++){ Cell cell = row.getCell(c); if(cell != null){ // 將區域編號的cell中的內容當做字符串處理 cell.setCellType(Cell.CELL_TYPE_STRING); /** 這裏省略了一部分代碼,根據自己的實體來做 */ if (c == 0) { } else if (c == 1) { oaGoalEntity.setDescription(cell.getStringCellValue().trim()); }else if(c == 15){ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = format.parse(cell.getStringCellValue().trim()); } catch (ParseException e) { e.printStackTrace(); } oaGoalEntity.setStartTime(date); }else if(c == 16){ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = format.parse(cell.getStringCellValue().trim()); } catch (ParseException e) { e.printStackTrace(); } oaGoalEntity.setEndTime(date); } } } goalList.add(oaGoalEntity); } return goalList; } /* * @Author YL * @Description //TODO 驗證Excel文件 * @Date 22:48 2018/8/16 * @Param [name] * @return boolean **/ public boolean validName(String name){ if(name == null || !(this.isExcel2003(name) || !this.isExcel2007(name))){ throw new ApplicationException("文件不是Excel格式"); } return true; } /* * @Author YL * @Description //TODO 判斷什麼版本的excel * @Date 22:46 2018/8/16 * @Param [name] * @return boolean **/ public boolean isExcel2003(String name){ return name.matches("^.+\\.(?i)(xls)$"); } public boolean isExcel2007(String name){ return name.matches("^.+\\.(?i)(sxls)$"); }