importación de archivos excel

   /**
     * 考核结果导入
     *
     * @param request
     * @param file
     * @return
     */
    @PostMapping("specialResultImport.do")
    @ResponseBody
    public RpcResult specialResultImport(HttpServletRequest request, MultipartFile file) {
    
    
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
    
    
            UserInfoVO user = UserHelper.getUser(request);
            Assert.notNull(user, "未获取到登录用户信息");
            String importType = request.getParameter("importType");
            log.info("考核结果导入 importType:{}", importType);
            if (StringUtils.isBlank(importType)) {
    
    
                return RpcResult.builder().success(false).code("4002").message("参数异常!").build();
            }

            TwdSpecialAssessmentResultVo resultVO = TwdSpecialAssessmentResultVo.builder()
                    .identification(importType)
                    .build();
            log.info("考核结果导入 :resultVO{}", JSON_BINDER.toJson(resultVO));
            this.checkRole(user, resultVO);

            if (StringUtils.isBlank(resultVO.getRoleCode())) {
    
    
                return RpcResult.builder().success(false).code("4021").message("暂无权限!").build();
            }
            if ("2720".equals(resultVO.getRoleCode())) {
    
    
                return RpcResult.builder()
                        .success(false)
                        .code("4022")
                        .message("管理员无法导入!")
                        .build();
            }

            String resultId = request.getParameter("resultId");
            log.info("考核结果导入 resultId:{}", resultId);
            if (StringUtils.isBlank(resultId)) {
    
    
                return RpcResult.builder()
                        .success(false)
                        .code("4003")
                        .message("参数异常")
                        .build();
            }
            long aLong = sysConfigHelper.valueOfSysDictElement(UPLOAD_DIC_KEY, SPECIAL_ASSESSMENT_MAX_SIZE, 10485760L);
            if (file.getSize() > aLong) {
    
    
                return RpcResult.builder()
                        .success(false)
                        .code("4004")
                        .message("上传的文件需在10M以内!")
                        .build();
            }
            String originalFilename = file.getOriginalFilename();
            String suffix = StringUtils.isNotBlank(originalFilename) ? originalFilename.substring(originalFilename.lastIndexOf(".") + 1) : "";
            if (StringUtils.isBlank(suffix)) {
    
    
                return RpcResult.builder()
                        .success(false)
                        .code("4005")
                        .message("未获取到文件后缀!").build();
            }
            String uploadType = sysConfigHelper.valueOfSysDictElement(UPLOAD_DIC_KEY, SPECIAL_ASSESSMENT_UPLOAD_TYPE, "xlsm");
            if (!uploadType.contains(suffix.toLowerCase())) {
    
    
                return RpcResult.builder()
                        .success(false)
                        .code("4006")
                        .message("导入失败,请检查文件格式!")
                        .build();
            }
            Workbook wb = null;
            //得到Excel工作表对象
            Sheet sheet = null;
            List<TwdSpecialAssessmentExportVo> listAll = new ArrayList<>();
            List<String> dataLists = new ArrayList<>();
            //导入标志
            boolean importFlag = true;
            String tipsStr = "";
            String str = "导入失败,必填项漏填";
            //校验错误数量
            int count = 0;
            //总导入数
            int totalImports = 0;
            if ("xlsm".equals(suffix.toLowerCase())) {
    
    
                log.info("读取excel表格开始");
                wb = WorkbookFactory.create(file.getInputStream());
                sheet = wb.getSheetAt(0);
                //总行数
                int trLength = sheet.getLastRowNum();
                log.info("总行数:{}", trLength);
                if (trLength >= 2) {
    
    
                    TwdSpecialAssessmentExportVo assessmentExportVO = null;
                    for (int i = 2; i <= trLength; i++) {
    
    
                        assessmentExportVO = new TwdSpecialAssessmentExportVo();

                        try {
    
    
                            //得到Excel工作表的行
                            Row row = sheet.getRow(i);
                            boolean rowEmpty = this.isRowEmpty(row);
                            log.info("考核结果导入 rowEmpty:{}", rowEmpty);
                            if (rowEmpty) {
    
    
                                continue;
                            }

                            totalImports++;

                            Cell cell8 = row.getCell((short) 8);
                            String jobNum = "";
                            if (null == cell8 || "".equals(cell8.toString())) {
    
    
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            } else {
    
    
                                cell8.setCellType(Cell.CELL_TYPE_STRING);
                                jobNum = cell8.getStringCellValue();
                                boolean jobNumEmpty = this.isJobNumEmpty(jobNum);
                                if (!jobNumEmpty) {
    
    
                                    dataLists.add(jobNum);
                                    importFlag = false;
                                    tipsStr = "导入失败,被考核人万信号不存在";
                                    count++;
                                    continue;
                                }
                            }

                            Cell cell0 = row.getCell((short) 0);
                            if (null == cell0 || "".equals(cell0.toString())) {
    
    
                                dataLists.add(jobNum);
                                tipsStr = str;
                                importFlag = false;
                                count++;
                                continue;
                            }

                            Cell cell1 = row.getCell((short) 1);
                            if (null == cell1 || "".equals(cell1.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }

                            Cell cell2 = row.getCell((short) 2);
                            if (null == cell2 || "".equals(cell2.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }

                            Cell cell3 = row.getCell((short) 3);
                            if (null == cell3 || "".equals(cell3.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }

                            Cell cell4 = row.getCell((short) 4);
                            if (null == cell4 || "".equals(cell4.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }

                            Cell cell5 = row.getCell((short) 5);
                            if (null == cell5 || "".equals(cell5.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }

                            Cell cell6 = row.getCell((short) 6);
                            if (null == cell6 || "".equals(cell6.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }
                            cell6.setCellType(Cell.CELL_TYPE_STRING);

                            Cell cell7 = row.getCell((short) 7);
                            if (null == cell7 || "".equals(cell7.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }

                            Cell cell9 = row.getCell((short) 9);
                            if (null == cell9 || "".equals(cell9.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }

                            Cell cell10 = row.getCell((short) 10);
                            if (null == cell10 || "".equals(cell10.toString())) {
    
    
                                dataLists.add(jobNum);
                                tipsStr = str;
                                importFlag = false;
                                count++;
                                continue;
                            }

                            Cell cell11 = row.getCell((short) 11);
                            if (null == cell11 || "".equals(cell11.toString())) {
    
    
                                dataLists.add(jobNum);
                                importFlag = false;
                                tipsStr = str;
                                count++;
                                continue;
                            }

                            Cell cell12 = row.getCell((short) 12);

                            Cell cell13 = row.getCell((short) 13);

                            if (null == cell13 || "".equals(cell13.toString())) {
    
    
                                assessmentExportVO.setEvaluationStep("");
                            } else {
    
    
                                cell13.setCellType(Cell.CELL_TYPE_STRING);
                                String evaluationStep = cell13.getStringCellValue();
                                if (evaluationStep.length() > 300) {
    
    
                                    dataLists.add(jobNum);
                                    importFlag = false;
                                    tipsStr = "评价及下一步已超过300个字符,请重新填写";
                                    count++;
                                    continue;
                                }
                                assessmentExportVO.setEvaluationStep(evaluationStep);
                            }

                            assessmentExportVO.setLevelName(cell0.getStringCellValue());
                            assessmentExportVO.setJudgeNone(cell1.getStringCellValue());
                            assessmentExportVO.setBranchName("无".equals(cell1.getStringCellValue()) ? "" : cell1.getStringCellValue());
                            assessmentExportVO.setGridName(cell2.getStringCellValue());
                            assessmentExportVO.setDeptName("无".equals(cell3.getStringCellValue()) ? "" : cell3.getStringCellValue());

                            cell4.setCellType(Cell.CELL_TYPE_STRING);
                            assessmentExportVO.setPostName(cell4.getStringCellValue());

                            assessmentExportVO.setStandPostName(cell5.getStringCellValue());
                            assessmentExportVO.setUserId(cell6.getStringCellValue());
                            assessmentExportVO.setLoginName(cell7.getStringCellValue());
                            assessmentExportVO.setLoginId(cell8.getStringCellValue());

                            String timeStr = "";
                            if (cell9.getCellType() == Cell.CELL_TYPE_NUMERIC && HSSFDateUtil.isCellDateFormatted(cell9)) {
    
    
                                timeStr = DateUtil.format(cell9.getDateCellValue(), "yyyy-MM-dd");
                            } else {
    
    
                                timeStr = cell9.getStringCellValue();
                            }
                            assessmentExportVO.setPostTime(timeStr);

                            cell10.setCellType(Cell.CELL_TYPE_NUMERIC);
                            assessmentExportVO.setScore(cell10.getNumericCellValue() + "");

                            assessmentExportVO.setEvaluationGrade(cell11.getStringCellValue());

                            if (null == cell12 || "".equals(cell12.toString())) {
    
    
                                assessmentExportVO.setUploadAssessmentReport("否");
                            } else {
    
    
                                cell11.setCellType(Cell.CELL_TYPE_STRING);
                                assessmentExportVO.setUploadAssessmentReport(cell12.getStringCellValue());
                            }

                        } catch (Exception e) {
    
    
                            log.error("解析excel出错 error : ", e.getMessage(), e);
                            return RpcResult.builder()
                                    .success(false)
                                    .code("4027")
                                    .message("模板不能被修改,请重新导出模板")
                                    .build();
                        }

                        assessmentExportVO.setIdentification(importType);
                        assessmentExportVO.setState("-1");
                        assessmentExportVO.setSorted(i);
                        assessmentExportVO.setIsDel("0");
                        assessmentExportVO.setCreateBy(user.getLoginId());
                        assessmentExportVO.setResultId(resultId);
                        assessmentExportVO.setCreateTime(new Date());

                        listAll.add(assessmentExportVO);
                    }
                } else {
    
    
                    return RpcResult.builder()
                            .success(false)
                            .code("4025")
                            .message("请填写数据后在上传!")
                            .build();
                }
            }
            log.info("考核结果导入 dataLists:[{}],importFlag:{},listAll:[{}],校验错误数量=count:{},totalImports:{}"
                    , JSON_BINDER.toJson(dataLists), importFlag, JSON_BINDER.toJson(listAll), count, totalImports);
            if (importFlag) {
    
    

                if (listAll.size() > 0) {
    
    

                    List<String> repeatCode = listAll.stream().collect(Collectors.groupingBy(TwdSpecialAssessmentExportVo::getLoginId, Collectors.counting()))
                            .entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());
                    log.info("考核结果导入 :[{}]", JSON_BINDER.toJson(repeatCode));
                    if (repeatCode.size() > 0) {
    
    

                        return RpcResult.builder()
                                .code("402919")
                                .success(false)
                                .message("有万信号重复,请检查后在导入")
                                .prifiled(String.valueOf(totalImports) + ";" + String.valueOf(repeatCode.size()))
                                .data(JSON_BINDER.toJson(repeatCode))
                                .build();
                    }

                    List<String> cityCompanyName = tWdSpecialAssessmentOrgService.getCityCompanyName();
                    log.info("考核结果导入 cityCompanyName:{}", JSON_BINDER.toJson(cityCompanyName));
                    if (null == cityCompanyName || cityCompanyName.size() <= 0) {
    
    
                        return RpcResult.builder()
                                .code("4030")
                                .success(false)
                                .message("未查询到指定区域本部/城市公司信息")
                                .build();
                    }
                    cityCompanyName.add("无");

                    List<String> centralSingleStoreName = tWdSpecialAssessmentOrgService.getCentralSingleStoreName();
                    log.info("考核结果导入 centralSingleStoreName:{}", JSON_BINDER.toJson(centralSingleStoreName));
                    if (null == centralSingleStoreName || centralSingleStoreName.isEmpty()) {
    
    
                        return RpcResult.builder()
                                .code("4031")
                                .success(false)
                                .message("未查询到指定中心/城市公司本部/单店信息")
                                .build();
                    }
                    centralSingleStoreName.add("无");

                    List<String> loginIds = listAll.stream()
                            .filter(s -> !cityCompanyName.contains(s.getJudgeNone()) || !centralSingleStoreName.contains(s.getGridName()))
                            .map(TwdSpecialAssessmentExportVo::getLoginId)
                            .collect(Collectors.toList());
                    log.info("考核结果导入 过滤不是指定的城市公司或单店后=loginIds:{}", JSON_BINDER.toJson(loginIds));
                    if (loginIds.size() > 0) {
    
    
                        return RpcResult.builder()
                                .code("402920")
                                .success(false)
                                .message("请检查导入文件中B列或C列是否与模板中提供单位名称完全一致").prifiled(String.valueOf(totalImports) + ";" + String.valueOf(loginIds.size()))
                                .data(JSON_BINDER.toJson(loginIds))
                                .build();
                    }

                    RpcResult rpcResult = twdSpecialAssessmentExportService.specialResultImport(listAll);
                    log.info("考核结果导入 rpcResult:{}", JSON_BINDER.toJson(rpcResult));

                    rpcResult.setData(String.valueOf(totalImports));
                    rpcResult.setPrifiled(String.valueOf(count));
                    return rpcResult;
                } else {
    
    
                    return RpcResult.builder()
                            .success(false)
                            .code("4026")
                            .message("导入失败,必填项漏填")
                            .build();
                }
            } else {
    
    
                return RpcResult.builder()
                        .code("402909")
                        .success(false).message(tipsStr).prifiled(String.valueOf(totalImports) + ";" + String.valueOf(count))
                        .data(JSON_BINDER.toJson(dataLists))
                        .build();
            }

        } catch (Exception e) {
    
    
            log.error("考核结果导入 error : ", e.getMessage(), e);
            return RpcResult.builder()
                    .success(false)
                    .code("4028")
                    .message("系统异常!")
                    .build();
        } finally {
    
    
            stopWatch.stop();
            log.info("考核结果导入 end 执行时长={}ms", stopWatch.getTotalTimeMillis());
        }
    }

/**
 * 校验是否是空行
 * @param row
 * @return
 */
public boolean isRowEmpty(Row row) {
    
    
    if(null != row){
    
    
        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
    
    

            Cell cell = row.getCell(i);

            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK){
    
    

                return false;

            }
        }
        return true;
    }
   return true;
}

   /**
     * 校验万信号是否存在
     * @param jobNum
     * @return
     */
    public boolean isJobNumEmpty(String jobNum){
    
    
        DmDHrStaffInfoVO infoByJobNum = dmDHrStaffInfoService.findDmDHrStaffInfoByJobNum(jobNum);
        return Objects.nonNull(infoByJobNum);
    }

Supongo que te gusta

Origin blog.csdn.net/chat_bot/article/details/126436124
Recomendado
Clasificación