首页 >excel操作 > 内容

处理导入的excel,并且把异常数据原因写在excel最后一列,并导出新的excel

2022年12月17日 22:40

1、Controller层逻辑处理

@RequestMapping("/batchInsertByExcel")public ResultData batchInsertByExcel(MultipartFile file, HttpServletResponse response){    ResultData resultData = new ResultData();    Workbook workbook = null;    try {        workbook = WorkbookFactory.create(file.getInputStream());        classTeacherRelationBusiness.batchInsertByExcel(workbook);        resultData.setSuccessStatus();    } catch (IOException e) {        HelpUtils.log_error(getClass(), "读取excel文件IO异常", e);        resultData.setErrorStatus(1, "读取excel文件异常");    } catch (InvalidArgumentException | BusinessException e) {        HelpUtils.log_error(getClass(), "解析excel文件业务异常", e);        resultData.setErrorStatus(1, e.getMessage());    }catch (ExcelParseErrorException e){        try {            String fileName = UUID.randomUUID().toString().replace("-","");            setResponseHeader(response, fileName.concat(".").concat(StringUtils.substringAfter(file.getOriginalFilename(), ".")));            OutputStream os = response.getOutputStream();            workbook.write(os);            os.flush();            os.close();        } catch (Exception e1) {            HelpUtils.log_error(getClass(), "解析excel文件系统异常", e);            resultData.setErrorStatus(1, "【批量导入班级老师失败】");        }    }catch (Exception e){        HelpUtils.log_error(getClass(), "解析excel文件系统异常", e);        resultData.setErrorStatus(1, "【批量导入班级老师失败】");    }    response.setHeader("X-Frame-Options","SAMEORIGIN");    return resultData;}

2、ClassTeacherRelationBusiness层逻辑处理

    public void batchInsertByExcel(Workbook workbook) {        List<ClassTeacherRelation> list = parseClassTeacherSheet(workbook);        if(list.isEmpty()){            HelpUtils.log_error(getClass(), "批量导入班级老师失败,没有数据");            throw new BusinessException("【批量导入班级老师失败】没有数据");        }        //批量插入        classTeacherRelationService.batchInsert(list);    }

3、对导入excel数据进行逻辑处理

private List<ClassTeacherRelation> parseClassTeacherSheet(Workbook workbook){        List<ClassTeacherRelation> caseList = new ArrayList<>();        List<Long> canOperateSchoolIds = getCanOperateSchoolIds();        if (CollectionUtils.isEmpty(canOperateSchoolIds)){            throw new BusinessException("【批量导入班级老师失败】,您没有对学校的操作权限");        }        //防重处理        Map<String, Object> map = new HashMap<>();        //学校缓存,一般一次只导入一个学校的数据        Map<String, SchoolInfo> schoolInfoMap = new HashMap<>();        boolean hasError = false;        Sheet sheet = workbook.getSheetAt(0);        int cellNum = ExcelUtils.removeErrorCell(sheet);        for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {            try {                Row row = sheet.getRow(rowIndex);                if(ExcelUtils.isRowEmpty(row)){                    continue;                }                //接收字段                ClassTeacherRelation classTeacher = new ClassTeacherRelation();                ClassInfo classInfo = new ClassInfo();                StaffInfo staffInfo = new StaffInfo();                readRow(row, classTeacher, classInfo, staffInfo);                //校验必填项                if (StringUtils.isEmpty(classInfo.getSchoolName())                        || classInfo.getClassYear() == null                        || StringUtils.isEmpty(classInfo.getGradeName())                        || classInfo.getClassNo() == null                        || classInfo.getClassYear() == null                        || StringUtils.isEmpty(staffInfo.getName())                        || StringUtils.isEmpty(staffInfo.getMobile())) {                    ExcelUtils.writeInTemplate("有必填项为空", rowIndex, cellNum, sheet);                    throw new InvalidArgumentException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,有必填项为空");                }                if(!RegexUtil.isMobile(staffInfo.getMobile())){                    ExcelUtils.writeInTemplate("手机号格式错误", rowIndex, cellNum, sheet);                    throw new InvalidArgumentException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,老师手机号格式错误");                }                if(classTeacher.getIsHeadMaster() != FscConstant.YES                        && StringUtils.isEmpty(classTeacher.getSubject())){                    ExcelUtils.writeInTemplate("非班主任任课科目必填", rowIndex, cellNum, sheet);                    throw new InvalidArgumentException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,非班主任任课科目必填");                }                //校验学校                SchoolInfo schoolInfo = schoolInfoMap.get(classInfo.getSchoolName());                if(schoolInfo == null){                    schoolInfo = schoolInfoService.selectSchoolId(classInfo.getSchoolName());                    schoolInfoMap.put(classInfo.getSchoolName(), schoolInfo);                }                if (schoolInfo == null) {                    ExcelUtils.writeInTemplate("该学校不存在", rowIndex, cellNum, sheet);                    throw new BusinessException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,该学校不存在");                }                if (!canOperateSchoolIds.contains(schoolInfo.getId())) {                    ExcelUtils.writeInTemplate("您没有该学校的操作权限", rowIndex, cellNum, sheet);                    throw new BusinessException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,您没有该学校的操作权限");                }                //校验年级                GradeInfo gradeInfo = gradeInfoService.queryByName(classInfo.getGradeName());                if (gradeInfo == null) {                    ExcelUtils.writeInTemplate("该年级不存在", rowIndex, cellNum, sheet);                    throw new BusinessException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,该年级不存在");                }                //校验班级                ClassInfo classParam = new ClassInfo();                classParam.setSchoolId(schoolInfo.getId());                classParam.setClassYear(classInfo.getClassYear());                classParam.setClassNo(classInfo.getClassNo());                classParam.setGradeId(gradeInfo.getId());                classParam.setStatus(StatusEnum.ENABLE.code);                List<ClassInfo> classList = classService.queryClassList(classParam);                if(CollectionUtils.isEmpty(classList) || classList.size() > 1){                    ExcelUtils.writeInTemplate("该班级不存在或存在一个以上相同班级", rowIndex, cellNum, sheet);                    throw new BusinessException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,该班级不存在或存在一个以上相同班级");                }                ClassInfo existClass = classList.get(0);                classTeacher.setClassId(existClass.getId());                //校验老师                StaffInfo staffParam = new StaffInfo();                staffParam.setStatus(StatusEnum.ENABLE.code);                staffParam.setSchoolId(schoolInfo.getId());                staffParam.setMobile(staffInfo.getMobile());;                staffParam.setName(staffInfo.getName());                List<StaffInfo> userList = staffInfoService.queryBySelective(staffParam);                if(CollectionUtils.isEmpty(userList)){                    ExcelUtils.writeInTemplate("该老师不存在,请检查学校、老师基本信息是否正确", rowIndex, cellNum, sheet);                    throw new BusinessException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,该老师不存在,请检查学校、老师基本信息是否正确");                }                classTeacher.setTeacherId(userList.get(0).getId());                if(classTeacher.getIsHeadMaster() == FscConstant.YES                        && existClass.getTeacherId() != null                        && existClass.getTeacherId().compareTo(classTeacher.getTeacherId()) != 0){                    ExcelUtils.writeInTemplate("该班级已经有班主任,请先移出", rowIndex, cellNum, sheet);                    throw new BusinessException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,该班级已经有班主任,请先移出");                }                //校验excel数据是否重复                String key = "" + classTeacher.getClassId() + classTeacher.getTeacherId();                if(map.get(key) != null){                    //excel存在相同身份证数据                    ExcelUtils.writeInTemplate("excel数据与第【"+map.get(key)+"】行数据重复", rowIndex, cellNum, sheet);                    throw new BusinessException("【批量导入班级老师失败】第【" + (rowIndex + 1) + "】行,excel数据与第【"+map.get(key)+"】行老师与班级重复");                }                map.put(key, rowIndex + 1);                caseList.add(classTeacher);            } catch (InvalidArgumentException | BusinessException e) {                hasError = true;                HelpUtils.log_error(getClass(), "{}", e.getMessage(), e);            }catch (Exception e){                hasError = true;                HelpUtils.log_error(getClass(), "【批量导入班级老师失败】第【{}】行", (rowIndex + 1), e);            }        }        if(hasError){            ExcelUtils.writeInTemplate("失败原因", 0, cellNum, sheet);            throw new ExcelParseErrorException("excel解析异常");        }        return caseList;    }

4、前端逻辑处理,上传excel

<input type="file" name="file" id="batch_upload_class_teacher_file" onchange="batchUploadClassTeacher(this)" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" style="display: none">function batchUploadClassTeacher(ele){    batchUploadExcelFile(ele, 'sec/class/teacher/batchInsertByExcel');}function batchUploadExcelFile(ele,url){    //excel格式验证    if (!ele || !$(ele).val()){        return;    }    var patn = /\.xls$|\.xlsx$/i;    if (!patn.test($(ele).val())) {        alert('提示:仅支持excel文件!');        $(ele).val('');        return;    }    if(url==undefined || url == ''){        alert('提示:上传路径错误!');        return;    }    showLoading();    var elementIds = ele.name; //flag为name属性名    $.ajaxFileUpload({        url: webUrlPrefix + url,//上传的url,根据自己设置        type: 'post',        secureuri: false, //一般设置为false        fileElementId: ele.id, // 上传文件的id、name属性名        dataType: 'json', //返回值类型,一般设置为json、application/json        elementIds: elementIds, //传递参数到服务器        success: function (data, status) {            console.log(data);            if(data.status.error == 0){                alert('批量导入数据成功');                getAllClassInfoByPage(1);            }else{                alert(data.status.message);            }            hideLoading();        },        error: function (data, status, e) {            alert("文件上传失败");            hideLoading();        }    });    hideLoading();}


参考文章:https://blog.csdn.net/damoneric_guo/article/details/110640840

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时候联系我们修改或删除,在此表示感谢。

特别提醒:

1、请用户自行保存原始数据,为确保安全网站使用完即被永久销毁,如何人将无法再次获取。

2、如果上次文件较大或者涉及到复杂运算的数据,可能需要一定的时间,请耐心等待一会。

3、请按照用户协议文明上网,如果发现用户存在恶意行为,包括但不限于发布不合适言论妄图

     获取用户隐私信息等行为,网站将根据掌握的情况对用户进行限制部分行为、永久封号等处罚。

4、如果文件下载失败可能是弹出窗口被浏览器拦截,点击允许弹出即可,一般在网址栏位置设置

5、欢迎将网站推荐给其他人,网站持续更新更多功能敬请期待,收藏网站高效办公不迷路。

      



登录后回复

共有0条评论