導入依賴
<!-- Excel導入導出 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-spring-boot-starter</artifactId> <version>4.1.0</version> </dependency>
實體類

ExcelUtil
import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; public class ExcelUtils { /** * excel 導出 * * @param list 數據 * @param title 標題 * @param sheetName sheet名稱 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param isCreateHeader 是否創建表頭 * @param response */ public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException { ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.HSSF); exportParams.setCreateHeadRows(isCreateHeader); defaultExport(list, pojoClass, fileName, response, exportParams); } /** * excel 導出 * * @param list 數據 * @param title 標題 * @param sheetName sheet名稱 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param response */ public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException { defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.HSSF)); } /** * excel 導出 * * @param list 數據 * @param title 標題 * @param sheetName sheet名稱 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param response */ public static void exportExcelXSSF(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException { defaultExportXSSF(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF)); } /** * excel 導出 * * @param list 數據 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param response * @param exportParams 導出參數 */ public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException { defaultExport(list, pojoClass, fileName, response, exportParams); } /** * excel 導出 * * @param list 數據 * @param fileName 文件名稱 * @param response */ public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException { defaultExport(list, fileName, response); } /** * 默認的 excel 導出 * * @param list 數據 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param response * @param exportParams 導出參數 */ private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException { Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); downLoadExcel(fileName, response, workbook); } /** * 默認的 excel 導出 * * @param list 數據 * @param pojoClass pojo類型 * @param fileName 文件名稱 * @param response * @param exportParams 導出參數 */ private static void defaultExportXSSF(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException { Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); downLoadExcelXSSF(fileName, response, workbook); } /** * 默認的 excel 導出 * * @param list 數據 * @param fileName 文件名稱 * @param response */ public static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException { Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); downLoadExcel(fileName, response, workbook); } /** * 下載 * * @param fileName 文件名稱 * @param response * @param workbook excel數據 */ private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLS.getValue(), "UTF-8")); workbook.write(response.getOutputStream()); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * 下載 * * @param fileName 文件名稱 * @param response * @param workbook excel數據 */ private static void downLoadExcelXSSF(String fileName, HttpServletResponse response, Workbook workbook) throws IOException { try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-Type", "application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8")); workbook.write(response.getOutputStream()); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * excel 導入 * * @param filePath excel文件路徑 * @param titleRows 標題行 * @param headerRows 表頭行 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException { if (StringUtils.isBlank(filePath)) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); params.setNeedSave(true); params.setSaveUrl("/excel/"); try { return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); } catch (NoSuchElementException e) { throw new IOException("模板不能為空"); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * excel 導入 * * @param file excel文件 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException { return importExcel(file, 1, 1, pojoClass); } /** * excel 導入 * * @param file excel文件 * @param titleRows 標題行 * @param headerRows 表頭行 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException { return importExcel(file, titleRows, headerRows, false, pojoClass); } /** * excel 導入 * * @param file 上傳的文件 * @param titleRows 標題行 * @param headerRows 表頭行 * @param needVerfiy 是否檢驗excel內容 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException { if (file == null) { return null; } try { return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * excel 導入 * * @param inputStream 文件輸入流 * @param titleRows 標題行 * @param headerRows 表頭行 * @param needVerfiy 是否檢驗excel內容 * @param pojoClass pojo類型 * @param <T> * @return */ public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException { if (inputStream == null) { return null; } ImportParams params = new ImportParams(); params.setTitleRows(titleRows); params.setHeadRows(headerRows); params.setSaveUrl("/excel/"); params.setNeedSave(true); params.setNeedVerify(needVerfiy); try { return ExcelImportUtil.importExcel(inputStream, pojoClass, params); } catch (NoSuchElementException e) { throw new IOException("excel文件不能為空"); } catch (Exception e) { throw new IOException(e.getMessage()); } } /** * Excel 類型枚舉 */ enum ExcelTypeEnum { XLS("xls"), XLSX("xlsx"); private String value; ExcelTypeEnum(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
導入之前先下載模板


導入
public List<String> userImport(MultipartFile file) throws IOException, FinanceException { List<UserManagementVo> list = null; try { list = ExcelUtils.importExcel(file, UserManagementVo.class); } catch (Exception e) { throw new FinanceException(111,"導入數據失敗"); } List<UserManagement> users = new ArrayList<>(); List<String> errorInfo = new ArrayList<>(); if (!ObjectUtils.isEmpty(list)) { for (int i = 0; i < list.size(); i++) { int num = i + 3; UserManagementVo us = list.get(i); if (us!=null && !ObjectUtils.isEmpty(us.getJobNumber()) && !ObjectUtils.isEmpty(us.getUserName() )&& !ObjectUtils.isEmpty(us.getSexs()) && !ObjectUtils.isEmpty(us.getDepartmentName()) && !ObjectUtils.isEmpty(us.getPostName())&& !ObjectUtils.isEmpty(us.getBankCard()) && !ObjectUtils.isEmpty(us.getBankOfDeposit()) && !ObjectUtils.isEmpty(us.getPositionName()) && !ObjectUtils.isEmpty(us.getEducation()) && !ObjectUtils.isEmpty(us.getAcademicDegree()) && !ObjectUtils.isEmpty(us.getPhone()) && !ObjectUtils.isEmpty(us.getStatuss()) && !ObjectUtils.isEmpty(us.getRoleIdName()) ){ String pattern = "[\u4e00-\u9fa5]+"; if (us.getUserName().length()>10){ // throw new FinanceException(111,"第" + num + "行 姓名超過10字符"); String s = "第" + num + "行 姓名超過10字符"; log.info(s); errorInfo.add(s); continue; } String pattern1 = "^[0-9a-zA-Z]+$"; boolean isMatch4 = Pattern.matches(pattern1, us.getJobNumber()); if (isMatch4==false){ String s = "第" + num + "行 工號只能輸入數字,字母及組合"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 工號只能輸入數字,字母及組合"); } if (us.getJobNumber().length()>20){ String s = "第" + num + "行 工號超過20字符"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 工號超過20字符"); } if (us.getBankCard().length()<15){ String s = "第" + num + "行 銀行卡號在16位和20位之間"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 銀行卡號在16位和20位之間"); } if (us.getBankCard().length()>20){ String s = "第" + num + "行 銀行卡號在16位和20位之間"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 銀行卡號在16位和20位之間"); } boolean isMatch2 = Pattern.matches(pattern1, us.getBankCard()); if (isMatch2==false){ String s = "第" + num + "行 銀行卡號只能輸入數字"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 銀行卡號只能輸入數字"); } boolean isMatch3 = Pattern.matches(pattern, us.getBankOfDeposit()); if (isMatch3==false){ String s = "第" + num + "行 開戶行只能輸入漢字"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 開戶行只能輸入漢字"); } if (us.getBankOfDeposit().length()>20){ String s = "第" + num + "行 開戶行超過20字符"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 開戶行超過20字符"); } if (us.getPositionName().length()>15){ String s = "第" + num + "行 職稱超過20字符"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 職稱超過20字符"); } if (us.getPhone().length()!=11 ){ String s = "第" + num + "行 電話輸入不正確"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 電話輸入不正確"); } //判斷 部門,崗位,學歷,學位,兼職。角色是否在系統中存在 //判斷工號是否重復 List<UserManagement> userManagement=userManagementMapper.queryJobNumbers(us.getJobNumber()); if (ObjectUtils.isEmpty(userManagement)){ //判斷部門 DepartmentManagement depts=departmentManagementMapper.departmentNameFlag(us.getDepartmentName()); if (!ObjectUtils.isEmpty(depts)){ //判斷崗位 PostManagement postManagement=postManagementMapper.queryByPostName(us.getPostName()); if (!ObjectUtils.isEmpty(postManagement)) { //判斷學歷 if (us.getEducation().equals("小學") || us.getEducation().equals("初中") || us.getEducation().equals("高中") || us.getEducation().equals("大專") || us.getEducation().equals("本科") || us.getEducation().equals("研究生") ){ //判斷學位 if(us.getAcademicDegree().equals("學士") || us.getAcademicDegree().equals("碩士") || us.getAcademicDegree().equals("博士")){ //判斷兼職部門 if (!ObjectUtils.isEmpty(us.getPartTimeJob())){ String[] depet=us.getPartTimeJob().split(","); for (String a:depet) { DepartmentManagement deptName = departmentManagementMapper.departmentNameFlag(a); if (ObjectUtils.isEmpty(deptName)){ String s ="第" + num + "行 輸入的兼職部門不存在,請核實后在輸入"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入的兼職部門不存在,請核實后在輸入"); } } } //兼職部門 String deptId = ""; List<String> list3 = Arrays.asList(us.getPartTimeJob().split(",")); List<String> newlist2 = new ArrayList<String>(list3); HashSet<String> hashSet2 = new HashSet<>(newlist2); if (newlist2.size() != hashSet2.size()) { String s ="第" + num + "行 輸入的兼職部門存在重復數據"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入的兼職部門存在重復數據"); } List<String> list2 = Arrays.asList(us.getPartPostJob().split(",")); List<String> newlist1 = new ArrayList<String>(list2); HashSet<String> hashSet1 = new HashSet<>(newlist1); if (newlist1.size() != hashSet1.size()) { String s ="第" + num + "行 輸入的兼職崗位存在重復數據"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入的兼職崗位存在重復數據"); } //判斷角色 List<String> list1 = Arrays.asList(us.getRoleIdName().split(",")); List<String> newlist = new ArrayList<String>(list1); HashSet<String> hashSet = new HashSet<>(newlist); if (newlist.size() != hashSet.size()) { String s ="第" + num + "行 輸入的角色存在重復數據"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入的角色存在重復數據"); } if(!ObjectUtils.isEmpty(us.getPartPostJob())){ String[] post=us.getPartPostJob().split(","); for (String b:post) { PostManagement post2=postManagementMapper.queryByPostName(b); if (ObjectUtils.isEmpty(post2)){ String s ="第" + num + "行 輸入的兼職崗位不存在,請核實后在輸入"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入的兼職崗位不存在,請核實后在輸入"); } } } UserManagement u = new UserManagement(); String[] role = us.getRoleIdName().split(","); String roleId=""; for (String r : role) { RoleList roleList = roleListMapper.queryByRoleNames(r); if (!ObjectUtils.isEmpty(roleList)) { roleId=roleId+","+roleList.getId(); u.setRoleId(String.valueOf(roleId.subSequence(1,roleId.length()))); }else { // throw new FinanceException(111, "第" + num + "行 輸入的角色在系統中不存在"); String s ="第" + num + "行 輸入的角色在系統中不存在"; log.info(s); errorInfo.add(s); continue; } } //判斷手機號 String phone = us.getPhone(); List<UserManagement> queryphone = userManagementMapper.queryphones(phone); if (!ObjectUtils.isEmpty(queryphone)){ String s ="第" + num + "行 輸入的手機號在系統中存在"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入的手機號在系統中存在"); } //判斷狀態 if (us.getStatuss().equals("在職") || us.getStatuss().equals("離職")) { u.setId(String.valueOf(snowFlake.nextId())); u.setUserName(us.getUserName()); if (us.getSexs().equals("男")) { u.setSex(1); } else if (us.getSexs().equals("女")){ u.setSex(2); }else{ String s ="第" + num + "行 性別只能輸入男或女"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 性別只能輸入男或女"); } u.setJobNumber(us.getJobNumber()); u.setDepartmentId(depts.getId()); u.setPostId(Long.valueOf(postManagement.getId())); u.setBankCard(us.getBankCard()); u.setBankOfDeposit(us.getBankOfDeposit()); u.setPositionName(us.getPositionName()); //學歷 String education = us.getEducation(); if (education.equals("小學")) { u.setEducation("1"); } else if (education.equals("初中")) { u.setEducation("2"); } else if (education.equals("高中")) { u.setEducation("3"); } else if (education.equals("大專")) { u.setEducation("4"); } else if (education.equals("本科")) { u.setEducation("5"); } else if (education.equals("研究生")) { u.setEducation("6"); } else if (education.equals("無")) { u.setEducation("0"); } //學位 String academicDegree = us.getAcademicDegree(); if (academicDegree.equals("學士")) { u.setAcademicDegree("1"); } else if (academicDegree.equals("碩士")) { u.setAcademicDegree("2"); } else if (academicDegree.equals("博士")) { u.setAcademicDegree("3"); } else if (academicDegree.equals("無")) { u.setAcademicDegree("0"); } u.setPhone(us.getPhone()); //\ 導入人員時兼職崗位/部門與主崗位/部門重復時進行判斷 //兼職崗位 String postId = ""; if (!ObjectUtils.isEmpty( us.getPartPostJob())){ String[] partPostJob = us.getPartPostJob().split(","); for (String q : partPostJob) { //查詢崗位id PostManagement postManagement1 = postManagementMapper.queryByPostName(q); if(postManagement1.getId().equals(postManagement.getId())){ String s ="第" + num + "行 輸入的兼職崗位與主崗位沖突"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111, "第" + num + "行 輸入的兼職崗位與主崗位沖突"); } postId = postId + "," + postManagement1.getId(); } u.setPartPostJob(String.valueOf(postId.subSequence(1, postId.length()))); } if (!ObjectUtils.isEmpty(us.getPartTimeJob())){ String[] de = us.getPartTimeJob().split(","); for (String w : de) { //\ 導入人員時兼職崗位/部門與主崗位/部門重復時進行判斷 //查詢部門id DepartmentManagement management = departmentManagementMapper.departmentNameFlag(w); if(management.getId().equals(depts.getId())){ String s ="第" + num + "行 輸入的兼職部門與主部門沖突"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111, "第" + num + "行 輸入的兼職部門與主部門沖突"); } deptId = deptId + "," + management.getId(); } u.setPartTimeJob(String.valueOf(deptId.subSequence(1, deptId.length()))); } if (us.getStatuss().equals("在職")) { u.setStatus(1); } else { u.setStatus(2); } u.setAccount(us.getPhone()); String pwd = new Md5Hash("666666", us.getPhone()).toBase64(); u.setPassword(pwd); u.setAdminFlag(1); u.setDeleteFlag(0); u.setEnable(2); u.setCreateTime(new Date()); users.add(u); // userManagementMapper.insert(u); // return "第" + num + "行 導入成功"; } else{ String s ="第" + num + "行 輸入的在職狀態有誤"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入的在職狀態有誤"); } }else{ String s ="第" + num + "行 輸入學位有誤"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入學位有誤"); } }else{ String s ="第" + num + "行 輸入學歷有誤"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入學歷有誤"); } }else{ String s ="第" + num + "行 系統中不存在該崗位"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 系統中不存在該崗位"); } }else{ String s ="第" + num + "行 系統中不存在該部門"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 系統中不存在該部門"); } }else{ String s ="第" + num + "行 輸入的工號在系統中存在"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 輸入的工號在系統中存在"); } }else{ String s ="第" + num + "行 系統中不存在或存在空格"; log.info(s); errorInfo.add(s); continue; // throw new FinanceException(111,"第" + num + "行 系統中不存在或存在空格"); } } if (errorInfo.size() < 1) { // 插入數據 userManagementMapper.insertList(users); return errorInfo; } else { // 錯誤行返回去 String string = JSONObject.toJSONString(errorInfo); return errorInfo; } }else{ throw new FinanceException(111,"未獲取到導入數據"); } }
<insert id="insertList" parameterType="java.util.List">
INSERT INTO user_management (
`id`,
`user_name`,
`sex`,
`Job_number`,department_id,post_id,bank_card,bank_of_deposit,
position_name,education,academic_degree,phone,part_post_job,part_time_job,status,
account,role_id,enable,create_user_id,delete_flag,admin_flag,password
)
values
<foreach collection="users" item="item" index="index" separator=",">
(
#{item.id},#{item.userName}, #{item.sex}, #{item.jobNumber}, #{item.departmentId},
#{item.postId}, #{item.bankCard}, #{item.bankOfDeposit}, #{item.positionName},#{item.education},
#{item.academicDegree}, #{item.phone}, #{item.partPostJob},#{item.partTimeJob}, #{item.status},
#{item.account}, #{item.roleId},#{item.enable}, #{item.createUserId}, #{item.deleteFlag}, #{item.adminFlag}, #{item.password}
)
</foreach>
</insert>