前端:
按钮:<a class="layui-btn layui-btn-sm layuiadmin-button-btn train-btn-css"id="uploadGuideExcel">Excel导入计划</a>
//
//导入计划upload.render({elem: '#uploadGuideExcel',
//修改为你的urlurl: domainName + '/trainingbase/importExcel', // 此处配置你自己的上传接口即可exts: 'xlsx',type: 'post',headers: {"Authorization": 'Bearer ' + localStorage.getItem("access_token")}, before: function (obj) { //obj参数包含的信息,跟 choose回调完全一致,可参见上文。layer.load(); //上传loading},error: function (index, upload) {layer.closeAll('loading'); //关闭loading}, done: function (res) {layer.closeAll('loading'); //关闭loadingif (res.code == 200) {myLayer.msg("上传成功");serchRef();} else {myLayer.Alert(res.msg);}}});
后端:
@PostMapping("/importExcel")public AjaxResult importExcel(MultipartFile file) throws IOException {UserVO userVO = userVOUtils.getUserVO(request);//校验权限,写自己的if(userVO != null && userVO.getTrainBaseList() != null){//培训基地是否只有一个if(userVO.getTrainBaseList().size() != 1){return AjaxResult.error("您的培训基地权限不唯一,无法上传");}}//培训基地id,没用可删String trainBaseid = userVO.getTrainBaseList().get(0);
//可以从这里开始//1. 加载数据ExcelReader reader = ExcelUtil.getReader(file.getInputStream());List<Map<String, Object>> mapList = reader.read(0, 1, reader.getRowCount() - 1);if(mapList==null || mapList.size()==0)return AjaxResult.error("导入数据不能为空");//2.校验数据列是否正确,写自己的Set<String> excelKey = mapList.get(0).keySet();Map<String,String> mapKey=new HashMap<>();if(!verifyDataColumn(excelKey,mapKey))return AjaxResult.error("列名称有误,请按规定模板导入!");//3.校验数据是否符合,写自己的String codeName = mapKey.get("unit_code");String s = vComPersonViewService.matchTrainInfo(mapList,trainBaseid);if(!s.isEmpty()){return AjaxResult.error(s);}//写入数据,mapList就是读取的到excel数据,其余参数写自己需要的boolean result = studentPlanService.importExcel(mapList,trainBaseid);return AjaxResult.success("导入成功",null);}//验证列名称是否一致private boolean verifyDataColumn(Set<String> excelKey, Map<String,String> mapKey) {//加载数据列List<Map<String, String>> importMap = new ArrayList<>();Map<String, String> map = new HashMap<>();map.put("column_name","姓名");map.put("column_name","学员编号");
// map.put("column_name","身份证号码");map.put("column_name","年度");map.put("column_name","培训状态");map.put("column_name","单元");map.put("column_name","轮转科室");map.put("column_name","轮转开始时间");map.put("column_name","轮转结束时间");importMap.add(map);boolean b=true;for (Map<String, String> map2 : importMap) {String column_name = map2.get("column_name");mapKey.put(map2.get("column_value"),column_name);if(!excelKey.contains(column_name)){b=false;}}return b;}