springboot導入excel文件信息到數據庫(上傳或更新)

有校驗手機號和郵箱以及其他的枚舉校驗。可以參考

Controller :

/**
     * 導入用戶數據
     * @param file
     * @return
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public UserCentreResponse importUser(@RequestPart("file") FilePart file) {
        UserCentreResponse userCentreResponse = new UserCentreResponse();
        List<String> errorList = new ArrayList<>();
        String fileName = null;
        if (file != null) {
            fileName = file.filename();//getOriginalFilename();

            try {
                errorList = userService.batchImport(fileName, file);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            userCentreResponse.setValue("導入成功!", errorList);
            return userCentreResponse;
        }else {
            return userCentreResponse.setError(400, "請導入文件!");
        }
    }

Service:

/**
     * 導入用戶信息
     * @param fileName
     * @param file
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> batchImport(String fileName, FilePart file) throws Exception {

        boolean notNull = false;
        List<User> userList = new ArrayList<User>();//用來存儲user
        List<String> errorList = new ArrayList<>();//存儲錯誤信息
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            errorList.add("上傳文件格式不正確");
            throw new RuntimeException ("上傳文件格式不正確");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        //上傳的文件的臨時存放目錄
        String tempDir=File.pathSeparator+"tmp";
        StringBuilder tempFilePath=new StringBuilder(tempDir).append(File.pathSeparator).append(UUID.randomUUID())
                .append("_").append(fileName);

        //將上傳的文件保存到臨時文件
        File tempFile=new File(tempFilePath.toString());
        Mono<Void> voidMono = file.transferTo(tempFile);
        InputStream is = new FileInputStream(tempFile);
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if(sheet != null){
            notNull = true;
        }
        User user;
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            String errorString = "(第("+(r+1)+")行導入失敗,";
            Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }

            user = new User();

            if (row.getCell(0).getCellType() != 1){
                errorList.add(errorString+"姓名請設爲文本格式!)");
                continue;
//                throw  new RuntimeException("導入失敗(第("+(r+1)+")行,姓名請設爲文本格式!)");
            }
            //用戶名
            String name = row.getCell(0).getStringCellValue();
            if (name == null || name.isEmpty()){
                errorList.add(errorString+"姓名未填寫!)");
                continue;
//                throw  new RuntimeException("導入失敗(第("+(r+1)+")行,姓名未填寫!)");
            }

            //賬戶類型
            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            String accountType = row.getCell(1).getStringCellValue();
            //類型
            Integer type = 0;
            String email = row.getCell(2).getStringCellValue();
            row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
            String phone = row.getCell(3).getStringCellValue();
            if (accountType != null || !accountType.isEmpty()){
                type = AccountTypeEnum.getCode(accountType);
                if (type == null){//1郵箱,2手機號
                    errorList.add(errorString+"賬戶類型填寫錯誤!請填寫{郵箱}或者{手機號}!)");
                    continue;
//                    throw  new RuntimeException("導入失敗(第("+(r+1)+")行,賬戶類型填寫錯誤!請填寫{郵箱}或者{手機號}!)");
                }else if(type == 1){
                    //郵箱
                    if (email == null || email.isEmpty()){
                        errorList.add(errorString+"賬戶類型爲郵箱!郵箱沒有填寫!)");
                        continue;
//                        throw  new RuntimeException("導入失敗(第("+(r+1)+")行,賬戶類型爲郵箱!郵箱沒有填寫!)");
                    }else {
                        if (!CheckUtil.isEmail(email)){
                            errorList.add("導入失敗(第("+(r+1)+")行,賬戶類型爲郵箱!郵箱填寫格式錯誤!)");
                            continue;
//                        throw  new RuntimeException(errorString+"賬戶類型爲郵箱!郵箱填寫格式錯誤!)");
                        }
                    }
                }else{
                    //手機號
                    if (phone == null || phone.isEmpty()){
                        errorList.add(errorString+"賬戶類型爲手機號!手機號沒有填寫!)");
                        continue;
//                        throw  new RuntimeException("導入失敗(第("+(r+1)+")行,賬戶類型爲手機號!手機號沒有填寫!)");
                    }else {
                        if (!CheckUtil.isPhone(phone)){
                            errorList.add(errorString+"賬戶類型爲手機號!手機號填寫格式錯誤!)");
                            continue;
//                        throw  new RuntimeException("導入失敗(第("+(r+1)+")行,賬戶類型爲手機號!手機號填寫格式錯誤!)");
                        }
                    }
                }
            }else {
                errorList.add(errorString+"賬戶類型未填寫!)");
                continue;
//                throw  new RuntimeException("導入失敗(第("+(r+1)+")行,賬戶類型未填寫!)");
            }

            //密碼
            String password = null;
            User userByName = this.getUserByName(name);
            row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
            password = row.getCell(4).getStringCellValue();
            //如果是null 則必填
            if (userByName == null){
                if (password == null || password.isEmpty()){
                    errorList.add(errorString+"用戶爲新增,密碼未填寫!)");
                    continue;
//                    throw  new RuntimeException("導入失敗(第("+(r+1)+")行,用戶爲新增,密碼未填寫!)");
                }
            }else {
                user.setId(userByName.getId());
            }

            //組織節點
            String org = row.getCell(5).getStringCellValue();
            List<String> orgString = Arrays.asList(org.split("-"));
            Integer orgId = null;
            Integer orgPid = null;
            if (orgString.get(2) != null) {
                Organization orgByName = organizationService.getOrgByName(orgString.get(2));
                if (orgByName != null) {
                    orgId = orgByName.getId();
                    orgPid = orgByName.getPid();
                    Result<OrganizationDetailDto> orgInfo = organizationService.getOrgInfo(orgPid);
                    String orgName = orgInfo.getData().getOrgName();
                    String parentName = orgInfo.getData().getParentName();

                    if (orgString.get(0).isEmpty() || !orgString.get(0).equals(parentName) || orgString.isEmpty() || !orgString.get(1).equals(orgName)){
                        errorList.add(errorString+"組織鏈不存在!)");
                        continue;
//                        throw  new RuntimeException("導入失敗(第("+(r+1)+")行,組織鏈不存在!)");
                    }

                }else {
                    errorList.add(errorString+"組織鏈不存在!)");
                    continue;
//                    throw  new RuntimeException("導入失敗(第("+(r+1)+")行,組織鏈不存在!)");
                }
            }else {
                errorList.add(errorString+"組織鏈不存在!)");
                continue;
//                throw  new RuntimeException("導入失敗(第("+(r+1)+")行,組織鏈不存在!)");
            }

            //用戶類型
            String userTypeString = row.getCell(6).getStringCellValue();
            Integer userType = UserTypeEnum.getCode(userTypeString);
            if (userType == 0){
                errorList.add(errorString+"用戶類型錯誤!(全職/兼職))");
                continue;
//                throw  new RuntimeException("導入失敗(第("+(r+1)+")行,用戶類型錯誤!(全職/兼職))");
            }

            //用戶狀態
            String userStatusString = row.getCell(7).getStringCellValue();
            Integer userStatus = UserStatusEnum.getCode(userStatusString);
            if (userStatus == null){
                errorList.add(errorString+"用戶狀態錯誤!(啓用/禁用))");
                continue;
//                throw  new RuntimeException("導入失敗(第("+(r+1)+")行,用戶狀態錯誤!(啓用/禁用))");
            }

            //入職時間
            Date date = null;
            if(row.getCell(8).getCellType() != 0){
                errorList.add(errorString+"入職日期格式不正確或未填寫)");
                continue;
//                throw new RuntimeException("導入失敗(第"+(r+1)+"行,入職日期格式不正確或未填寫)");
            }else{
                date = row.getCell(8).getDateCellValue();
            }

            //寫入數據庫
            user.setName(name);//用戶名
            user.setAccountType(type);//賬號類型
            user.setEmail(email);//郵箱
            user.setPhone(phone);//手機號
            user.setPassword(password);//密碼
            user.setOrgId(orgId);//組織節點
            user.setTypeId(userType);//用戶類型
            user.setStatus(userStatus);//用戶狀態
            user.setEntryTime(date);//入職時間
            if (userByName != null){
                userMapper.updateByPrimaryKeySelective(user);
            }else {
                userMapper.insertSelective(user);
            }

        }

        if (!tempFile.delete()){//刪除臨時文件
            log.warn("刪除臨時文件{}失敗.....",tempFilePath);
        }

        return errorList;
    }

excel文件:
在這裏插入圖片描述

數據庫結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章