/**
* 業務需求說明:
* 1 批量導入成員 並且 自主創建賬號
* 2 校驗數據格式 且 重複導入提示 已被佔用
* 3 導入手機相同 則更新源有信息
* 4 返回錯誤信息
*/
jsp文件 部分 瀏覽 以及功能鍵 代碼:
1 <div class="modal-body" style="position: relative;"> 2 <form class="" role="form" id="upload_form"> 3 <select class="form-control m-b" id="upload_dept" name="uploadDept"> 4 </select> 5 <div class="input-group"> 6 <input type="text" class="form-control input-sm" name="upload_filename"> 7 <div class="input-group-btn"> 8 <button type="button" class="btn btn-sm btn-primary"> 9 瀏覽 10 </button> 11 </div> 12 </div> 13 <!-- 選擇上傳文件按鈕 type類型指定爲 file accept 可以在瀏覽過程中 進行過濾顯示 支持多個用逗號隔開 --> 14 <!-- 選擇文件後顯示文件名稱 對更改事件綁定了事件監聽器 selectUploadFile(this) 此框按鈕id爲: upload_file --> 15 <input type="file" id="upload_file" onchange="selectUploadFile(this)" name="uploadFile" accept=".xls,.xlsx" class="input-fzliulan"> 16 </form> 17 </div> 18 <div class="modal-footer"> 19 <button type="button" id="btn_upCancel" class="btn btn-white" data-dismiss="modal">關閉</button> 20 <button type="button" id="btn_upSubmit" class="btn btn-success pdlr16"><span id="uploadTxt">導入</span><img id="loadingImg" style="display: none" src="<%=contextPath%>/resource/images/loading.gif" /></button> 21 </div>
comm.jsp文件定義的變量:
1 var userId = '<c:out value="${sessionScope.USER.userId}" />'; 2 var orgId = '<c:out value="${sessionScope.ORG.orgId}" />'; 3 var authLevel = '<c:out value="${sessionScope.USER.authLevel}" />'; 4 var userType = '<c:out value="${sessionScope.USER.type}" />'; 5 var orgAmount= '<c:out value="${sessionScope.AGENT.orgAmount}" />'; 6 var loginUser = {userId: userId, orgId: orgId, authLevel: authLevel, type: userType ,orgAmount:orgAmount};
頁面js:
1 $(function(){ 2 bindEvent(); 3 }) 4 /** 爲頁面按鈕綁定事件 5 */ 6 function bindEvent(){ 7 /** 8 * 顯示上傳文件名稱 9 * @param fileObj 10 */ 11 function selectUploadFile(fileObj){ 12 var fullPath = $(fileObj).val(); 13 var index = fullPath.lastIndexOf('\\') + 1; 14 var fileName = fullPath.substring(index); 15 $('input[name="upload_filename"]').val(fileName); 16 } 17 18 19 20 $('#downLoadTemplate').click(function(){ //下載模板按鈕的監聽器 21 var url = webContext + '/file\\template\\組織用戶信息模板.xlsx'; 22 downloadFile(url) 23 }); 24 25 /** 26 * 上傳文件 27 */ 28 29 $('#btn_upSubmit').click(function(){ 30 var valid = uploadValidator.checkForm(); //檢測傳單內容輸入是否有問題 31 if(!valid){ 32 uploadValidator.showErrors(); 33 } else{ //檢測成功 34 $('#uploadTxt').text(''); 35 $('#loadingImg').show(); //按鈕換成動畫效果圖片 36 /** 準備參數: */ 37 var orgId = loginUser.orgId; //但錢用戶的組織id 38 var deptId = $('#upload_dept').val(); // 選框中選擇的部門id 39 var password = hex_md5('123456');// 默認密碼 進行加密 40 var param = {orgId: orgId, deptId: deptId, password: password}; //ajax傳輸 攜帶json詳細信息 41 var url = webContext + '/org/uploadOrgUser'; // /** 使用ajaxFileUpload */ 42 $.ajaxFileUpload({ 43 url: url, //用於文件上傳的服務器端請求地址 44 secureuri: false, //是否需要安全協議,一般設置爲false 45 fileElementId: 'upload_file', //文件上傳域的ID 就是選定文件的 type=file的input框的id ajaxFileUpload 會幫我們把他分裝到ajax請求的 攜帶對象域中去 46 dataType: 'json', //返回值類型 一般設置爲json 47 type: 'post', 48 data: param, 49 success:function(){ 50 //成功的success 回調方法等業務流程結束後再寫 51 //先留已空白 52 } 53 }) 54 } 55 }) 56 }
項目使用SpringMVC :
其controller爲:
1 //-----------------------------------MVC 的控制器---------------------- 2 //Controller爲: 3 @Controller 4 @RequestMapping("/org") 5 public class OrgController extends BaseController { 6 7 @Autowired 8 private IOrgService orgService; 9 10 @RequestMapping("/uploadOrgUser") 11 @ResponseBody 12 public Map<String, Object> uploadOrgUser(HttpServletRequest request){ 13 Map<String, Object> map = new HashMap<String, Object>(); 14 String flag = "failure"; 15 String msg = "上傳成功"; 16 MultipartHttpServletRequest mtRequest = (MultipartHttpServletRequest) request;//多部分httpRquest對象 是HttpServletRequest類的一個子類接口 支持文件分段上傳對象 17 Integer orgId = RequestUtil.getIntParam(mtRequest, "orgId"); //組織id 18 Integer deptId = RequestUtil.getIntParam(mtRequest, "deptId"); //選取部門id 19 String password = RequestUtil.getStringParam(request, "password"); // 初始密碼 已被md5加密 20 MultipartFile upFile = mtRequest.getFile("uploadFile"); // 直接獲取文件對象 21 if(null == upFile || upFile.getSize()==0){ //文件不存在的情況 22 msg = "上傳文件不存在或爲空文件"; 23 map.put("flag", flag); 24 map.put("msg", msg); 25 return map; //返回錯誤信息 26 } 27 String targetPath = request.getServletContext().getRealPath("/file/upload"); //獲取服務器 中file/update 的 url地址 28 map = orgService.uploadOrgUser(targetPath, orgId, deptId, password, upFile); //調用實現類 返回 界面消息 對象 29 return map; 30 } 31 }
--業務層接口--說明:
1 public interface IOrgService { 2 /** 3 * @param targetPath 4 * @param orgId 5 * @param deptId 6 * @param password 7 * @param upFile 8 * @return 9 */ 10 public Map<String, Object> uploadOrgUser(String targetPath, Integer orgId, Integer deptId, String password, MultipartFile upFile); 11 }
--業務層實現類:
1 //業務層實現類: 2 @Service("orgService") 3 public class OrgServiceImpl extends BaseService implements IOrgService { 4 5 @Autowired 6 private IOrgDao orgDao; 7 8 @Autowired 9 private IUserDao userDao; 10 11 @Autowired 12 private IDeptDao deptDao; 13 14 @Autowired 15 private IOrgUserDao orgUserDao; 16 17 @Autowired 18 private IServiceAuthDao authDao; 19 20 /** 批量導入 業務方法 **/ 21 public Map<String, Object> uploadOrgUser(String targetPath, Integer orgId, Integer deptId, String password, MultipartFile upFile) { 22 Map<String,Object> rm = new HashMap<String,Object>(); 23 String flag ="failure"; 24 String msg = "上傳失敗"; 25 File f = new File(targetPath) //實例硬盤中文件夾(路徑)對象 26 if(!f.exists()){//判斷此路徑/文件夾是否存在 27 f.mkdirs(); //如果不存在 則創建文件夾/目錄 28 } 29 String originalName = upFile.getOriginalFilename();//獲取文件對象原始文件名 30 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 31 String tag = sdf.format(new Date()); 32 String upFileName = targetPath + File.separator+tag+"_"+originalName;// 拼接出文件的要存儲的位置(全路徑) 33 File file = new File(upFileName);//創建 內存中的File對象 34 if(file.exists()){ //判斷是否存在 35 file.delete();//如果有重名文件存在 就刪除文件 36 // 這個對象對應的硬盤必須刪 不能存在 如果已經存在 則會拋出 37 // IOException異常 38 } 39 List<OrgUser> orgUsers = null; 40 List<User> users = null; 41 List<RowData> offedData = null; //List 集合對象準備 42 try{ 43 upFile.transferTo(file);//轉存文件 寫入硬盤 //這個 本質還是一樣的打開流傳文件 需要注意 file對應的硬盤中的文件不能存在 需要刪除 否則會拋出 文件已經存在且不能刪除 異常 44 // 校驗上傳數據 45 /** 輔助方法一 **/ 46 Map<String,Object> validData = validUpload(file,orgId,deptId);// 校驗數據 分類 返回 map形式 47 users = (List<User>) validData.get("PASSED_USERS"); //通過的user 是向 m_user 表的 48 orgUsers = (List<OrgUser>) validData.get("PASSED_ORGUSERS"); // 是向 m_org_user 表的 49 offedData = (List<RowData>) validData.get("OFFED_ROW"); //? 50 int rowNum = (Integer) validData.get("DATA_SIZE"); // excle 數據總長度 51 rm.put("ROW_COUNT", rowNum);//業務類的總長度 52 53 List<OrgUser> ous = orgUserDao.getOrgUsers(orgId);//獲取組織的所有用戶 54 ServiceAuth sa = new ServiceAuth(); //權限對象 55 sa.setOrgId(orgId); // 設置組織id 56 sa.setServiceCode(Sys.GROUP_ORG); //設置服務編碼 多用戶版基礎服務 57 sa.setType(Sys.TYPE_BUY); //設置 類型 爲購買類型 58 ServiceAuth nSa = authDao.getOrgServiceAuthInfo(sa); //獲取組織服務等級 詳細信息 59 int actSize = ous.size(); // 當前組織已有用戶的總長度 60 int license = nSa.getLicense(); // 組織上限人數 61 int totalNum = 0; //設置總數爲 0 62 63 Org o = orgDao.getOrgById(orgId); //獲取組織對象 64 Date duration = DateFormater.stringToDate(o.getDuration(), "yyyy-MM-dd"); //獲取服務到期時間 65 //上數據庫插入數據 66 if(null!=users && !users.isEmpty()){ 67 totalNum = actSize + users.size(); //總數現在等於 添加人數和已有人數 68 if(totalNum < license){//上傳人數和原有人數之和小於組織服務人數上限 69 for(int i=0; i<users.size(); i++){ 70 User u = users.get(i); 71 u.setPassword(password); 72 OrgUser ou = orgUsers.get(i); 73 userDao.addUser(u); 74 //添加到微信企業號 75 addCpUser(u); 76 //添加個人空間 77 Org selfOrg = new Org(); 78 selfOrg.setAdminName(u.getUserName()); 79 selfOrg.setType(Sys.ORG_TYPE_PER); 80 selfOrg.setState(Sys.ORG_VERIFY_1); 81 selfOrg.setAdminId(u.getUserId()); 82 selfOrg.setAdminName(u.getUserName()); 83 selfOrg.setDuration(duration); 84 selfOrg.setDel(Sys.UN_STOPED); 85 selfOrg.setCreateTime(new Date()); 86 selfOrg.setUpdateTime(new Date()); 87 selfOrg.setIdparent(0); 88 orgDao.addOrg(selfOrg); 89 Dept d = new Dept(); 90 d.setDeptId(0); 91 addOrgUserRelation(selfOrg, d, u); 92 if(null!=u.getUserId() && u.getUserName().equals(ou.getOrgUserName())){ 93 ou.setUserId(u.getUserId()); 94 orgUserDao.addOrgUser(ou); 95 } 96 } 97 rm.put("PASSED_COUNT", users.size());//成功數據 98 } else { 99 rm.put("ORG_LICENSE", license); //上限 100 rm.put("ORG_ACTSIZE", actSize); // 101 rm.put("OVER_LICENSE", totalNum - license); 102 } 103 104 } 105 int offedCount = 0; 106 if(null!= offedData && !offedData.isEmpty()){ 107 offedCount = offedData.size(); 108 rm.put("OFFED_DATA", offedData); 109 } 110 rm.put("OFFED_COUNT", offedCount); 111 112 flag = "success"; 113 msg = "上傳成功"; 114 } catch (Exception e2) { 115 logger.error("Exception while uploadOrgUser", e2); 116 } 117 rm.put("flag", flag); 118 rm.put("msg", msg); 119 120 return rm; 121 122 } 123 }
----------------------------------------------------------------------------------------------------------------------------------------------
//輔助方法清單:
1 //*************************** 輔助方法一 ***************************************************************** 2 /** 3 * 校驗上傳文件 4 * 參數:文件對象 5 * 組織id 6 * 部門id 7 */ 8 private Map<String, Object> validUpload(File uploadFile, Integer orgId, Integer deptId) throws Exception{ 9 Map<String, Object> map = new HashMap<String, Object>(); 10 List<User> passed = null; 11 List<User> offed = null; 12 List<String> mobileList = userDao.getAllActiveMobile();//爲了防止已註冊用戶再次註冊 13 List<String> emailList = userDao.getAllActiveEmail();// 現在還是查詢出所有的 ------需要優化標記 14 //獲取上傳的excel中的數據 15 //******輔助方法二********* 16 ExcelData uploaddata = getUploadUserData(uploadFile);//獲取內存中解析好的excle數據對象 17 //校驗上傳數據 18 //******輔助方法三********* 19 Map<String, Object> dataMap = validUploadData(orgId, deptId, uploaddata, mobileList, emailList); //返回的是數據對象 20 21 return dataMap; 22 }
//*************************** 輔助方法二 ***************************************************************** /** * 獲取上傳文件的數據 * @param uploadFile * @return * @throws Exception */ private ExcelData getUploadUserData(File uploadFile) throws Exception{ List<User> list = new ArrayList<User>(); String[] columnKey = {"userName", "mobile", "phone", "email", "QQ", "weixin", "job", "dept", "note"}; int startRow = 1; ExcelData uploadData = FileUtil.parseExcelFile(uploadFile, startRow, columnKey);//將要拋出異常 return uploadData; } }
1 //*************************** 輔助方法三 ***************************************************************** 2 /** 3 * 方法說明: 4 * 校驗上傳數據 5 * 6 * 7 * @param orgId 其應該所屬的組織 8 * @param deptId 所選的部門id 9 * @param excelData excel表格數據對象 10 * @param mobiles 所有的手機號碼 集合 用來判斷手機是否註冊 11 * @param emails 所有的郵箱號碼 集合 12 * @return 13 */ 14 private Map<String, Object> validUploadData(Integer orgId, Integer deptId,ExcelData excelData, List<String> mobiles, List<String> emails) { 15 Map<String, Object> map = new HashMap<String, Object>(); 16 List<RowData> passed = new ArrayList<RowData>(); 17 List<User> passedUsers = new ArrayList<User>(); // 通過驗證的 到 m_user 18 List<OrgUser> passedOrgUsers = new ArrayList<OrgUser>(); //通過驗證的 到m_org_user 19 List<RowData> offed = new ArrayList<RowData>(); 20 List<RowData> rows = null;// 所有數據 21 Date createTime = new Date();//創建時間 22 Date updateTime = new Date(); //更新時間 23 List<Dept> deptList = null; //當前組織的所有部門的 list集合 24 Map<String, Dept> deptMap = new HashMap<String, Dept>(); 25 if(null != excelData && null != excelData.getRows() && !excelData.getRows().isEmpty()){ //如果傳入對象不爲空 26 rows = excelData.getRows(); //獲取對象中的所有數據 類型應該是List集合 每個元素應該是一行數據 即:RowData 27 map.put("DATA_SIZE", rows.size());// 設置總數據有多少條 28 List<String> excelMobiles = new ArrayList<String>(); //用於存放excle表格中的電話號碼 29 List<String> excelEmails = new ArrayList<String>(); //用於存放excle表格中的郵箱號碼 30 deptList = deptDao.getDeptsByOrgId(orgId);//獲取所有部門? 31 for(Dept dept:deptList){ 32 String deptName = dept.getDeptName(); 33 deptMap.put(deptName, dept);//轉成map了 34 } 35 rowloop: //行循環跳出座標準備 36 for (int i = 0; i < rows.size(); i++) {//循環便利數據 37 OrgUser orgUser = new OrgUser(); //組織用戶 實例化對象準備 38 User user = new User(); //用戶 POJO準備 39 //獲取行數據 40 RowData r = rows.get(i); // 獲取行數據 41 int rowIndex = r.getRowIndex(); // 獲取當前行是第幾行 42 List<CellData> cells = r.getCells(); //獲取當前行的所有數據 cell 的s 43 boolean flag = true; 44 String userName="",mobile="",phone="",email="",qq="",weixin="",job=""; 45 int mIndex = 0; 46 int eIndex = 0; 47 columnloop: //列循環跳出座標準備 48 for (int j = 0; j < cells.size(); j++) { // 每一行單元格數據 遍歷 49 CellData c = cells.get(j); //獲取出當前的 數據獨立單元格 50 String key = c.getKey(); //屬於哪一列? 51 String cellValue = c.getCellValue(); //值 52 if("userName".equals(key)){ 53 userName = cellValue; 54 if(StringUtil.isBlank(cellValue)){ 55 flag = false; 56 c.setPassed(0); 57 c.setExtraInfo("用戶姓名不能爲空"); 58 continue columnloop; 59 } 60 user.setUserName(cellValue); 61 orgUser.setOrgUserName(cellValue); 62 } else if("mobile".equals(key)){ //手機相關驗證 63 mIndex = j; 64 mobile = cellValue; 65 if(!StringUtil.isBlank(cellValue)){ 66 if(!Validator.isMobile(cellValue)){ //校驗手機格式 67 flag = false; 68 c.setPassed(0); 69 c.setExtraInfo("不正確的手機號"); 70 continue columnloop; 71 } 72 73 if(mobiles.contains(cellValue.trim())){// 比對數據庫中的 是否已被註冊 74 flag = false; 75 c.setPassed(0); 76 c.setExtraInfo("該手機號已經被使用"); 77 continue columnloop; 78 } 79 if(excelMobiles.contains(cellValue.trim())){ // 當前表格 數據有重複 80 flag = false; 81 c.setPassed(0); 82 c.setExtraInfo("重複的手機號碼"); 83 continue columnloop; 84 } 85 user.setLoginName(cellValue); 86 } 87 user.setMobile(cellValue); 88 } else if("phone".equals(key)){ //暫無 89 phone = cellValue; 90 if(!StringUtil.isBlank(cellValue)){ 91 // if(!Validator.isPhone(cellValue)){ 92 // flag = false; 93 // c.setPassed(0); 94 // c.setExtraInfo("不正確的電話號"); 95 // continue columnloop; 96 // } 97 } 98 user.setPhone(cellValue); 99 } else if("email".equals(key)){ // 郵箱相關驗證 100 eIndex = j; 101 email = cellValue; 102 if(!StringUtil.isBlank(cellValue)){ 103 if(!Validator.isEmail(cellValue)){ 104 flag = false; 105 c.setPassed(0); 106 c.setExtraInfo("郵箱格式不正確"); 107 continue columnloop; 108 } 109 if(emails.contains(cellValue.trim())){ 110 flag = false; 111 c.setPassed(0); 112 c.setExtraInfo("該郵箱已經被使用"); 113 continue columnloop; 114 } 115 if(excelMobiles.contains(cellValue.trim())){ 116 flag = false; 117 c.setPassed(0); 118 c.setExtraInfo("重複的郵箱"); 119 continue columnloop; 120 } 121 user.setLoginName(cellValue); 122 } 123 user.setEmail(cellValue); 124 } else if("QQ".equals(key)){ 125 qq = cellValue; 126 user.setQq(cellValue); 127 } else if("weixin".equals(key)){ 128 weixin = cellValue; 129 user.setWeixin(cellValue); 130 } else if("job".equals(key)){ 131 job = cellValue; 132 orgUser.setPosition(cellValue); 133 //暫無 134 } else if("note".equals(key)){ 135 user.setNote(cellValue); 136 } else if("dept".equals(key)) { 137 if(!StringUtil.isBlank(cellValue) && null!=deptMap.get(cellValue.trim())){ 138 Dept d = deptMap.get(cellValue.trim()); 139 orgUser.setDeptId(d.getDeptId()); 140 } else { 141 orgUser.setDeptId(deptId); 142 } 143 } else { 144 //暫無 145 } 146 } 147 //校驗手機與郵箱是否同時爲空 148 if(StringUtil.isBlank(mobile) && StringUtil.isBlank(email)){ 149 flag = false; 150 CellData mobileCell = cells.get(mIndex);//所屬的 行和列 151 CellData emailCell = cells.get(eIndex); 152 mobileCell.setPassed(0); //設置是否通過了校驗的標識 注:此標識是對單元格數據進行設置的 153 mobileCell.setExtraInfo("手機與郵箱不能同時爲空"); //沒有通過校驗 進行 154 emailCell.setPassed(0); 155 emailCell.setExtraInfo("手機與郵箱不能同時爲空"); 156 } 157 if(flag){ //驗證通過的話 158 //初始化user 和 orgUser對象 159 user.setDefaultOrgId(orgId); 160 user.setMultiLogin(0); 161 user.setIsDistributor(0); 162 user.setSrcOrg(orgId); 163 user.setMobileBinded(0); 164 user.setEmailBinded(0); 165 user.setUtype(0); 166 user.setUpdateTime(updateTime); 167 user.setCreateTime(createTime); 168 user.setDel(Sys.UN_STOPED); 169 user.setType(2); 170 user.setSource(1); 171 user.setIspremiumuser(true); 172 // user.setNote("上傳生成用戶"); 173 user.setPassword("123456"); 174 175 orgUser.setOrgId(orgId); 176 // orgUser.setDeptId(deptId); 177 orgUser.setCreateTime(createTime); 178 orgUser.setUpdateTime(updateTime); 179 orgUser.setDel(Sys.UN_STOPED); 180 orgUser.setState(1); 181 orgUser.setIsDataCommissioner(0); 182 orgUser.setIsMarketCommissioner(0); 183 //向通過list裏添加數據 184 passedUsers.add(user); //添加到通過的 數據列表中去 185 passedOrgUsers.add(orgUser); 186 if(!StringUtil.isBlank(mobile)){ 187 excelMobiles.add(mobile); //添加到 準備的 list中去 以防下面重複數據 在上面驗證 188 } 189 if(!StringUtil.isBlank(email)){ 190 excelEmails.add(email); 191 } 192 } else { 193 offed.add(r); 194 } 195 196 } 197 } 198 map.put("PASSED_USERS", passedUsers); // 199 map.put("PASSED_ORGUSERS", passedOrgUsers); 200 map.put("OFFED_ROW", offed); 201 return map; 202 }
==============================================================================================
// 輔助工具類:
1 package com.SS.util; 2 3 import com.SS.util.excel.CellData; 4 import com.SS.util.excel.ExcelData; 5 import com.SS.util.excel.RowData; 6 import com.sun.image.codec.jpeg.JPEGCodec; 7 import com.sun.image.codec.jpeg.JPEGEncodeParam; 8 import com.sun.image.codec.jpeg.JPEGImageEncoder; 9 import org.apache.log4j.Logger; 10 import org.apache.poi.hssf.usermodel.HSSFCell; 11 import org.apache.poi.hssf.usermodel.HSSFRow; 12 import org.apache.poi.hssf.usermodel.HSSFSheet; 13 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 14 import org.apache.poi.ss.usermodel.Cell; 15 import org.apache.poi.xssf.usermodel.XSSFCell; 16 import org.apache.poi.xssf.usermodel.XSSFRow; 17 import org.apache.poi.xssf.usermodel.XSSFSheet; 18 import org.apache.poi.xssf.usermodel.XSSFWorkbook; 19 20 import javax.imageio.ImageIO; 21 import java.awt.*; 22 import java.awt.image.BufferedImage; 23 import java.io.*; 24 import java.util.ArrayList; 25 import java.util.List; 26 27 /** 28 * 文件操作工具類 29 */ 30 public class FileUtil { 31 32 private Logger logger = Logger.getLogger(FileUtil.class); 33 34 /** 35 * 獲取文件的後綴名稱 36 * @param file 37 * @return 38 */ 39 public static String getFileSuffix(File file){ 40 String suffix = ""; 41 if(null != file && StringUtil.isBlank(file.getName())){ 42 String fileName = file.getName(); 43 suffix = fileName.substring(fileName.lastIndexOf(".")); 44 } 45 46 return suffix; 47 } 48 49 /** 50 * 解析excel文件 51 * @param file excel文件 52 * @param startRow 起始行 0爲第一行 53 * @param columnKey 每列對應的key值 54 * @return 55 */ 56 public static ExcelData parseExcelFile(File file, int startRow, String[] columnKey){ 57 List<RowData> rows = null; 58 ExcelData excelData = new ExcelData(); 59 try { 60 if(null==file || !file.exists() || columnKey.length<1){ 61 return excelData; 62 } 63 String fileName = file.getName(); 64 excelData.setFileName(fileName); 65 if(fileName.endsWith("xls")){ 66 rows = parse2003Excel(file, startRow, columnKey); 67 } else if(fileName.endsWith("xlsx")){ 68 rows = parse2007Excel(file, startRow, columnKey); 69 } else { 70 throw new RuntimeException("Unknown file type : "+fileName); 71 } 72 excelData.setRows(rows); 73 } catch (Exception e) { 74 e.printStackTrace(); 75 } 76 return excelData; 77 } 78 79 /** 80 * 解析2003 excel文件 81 * @param file excel文件 82 * @param startRow 起始行 0爲第一行 第一行已經有 頭了 83 * @param columnKey 每列對應的key值 84 * @return 85 */ 86 private static List<RowData> parse2003Excel(File file, int startRow, String[] columnKey){ 87 List<RowData> rows = new ArrayList<RowData>(); 88 try { 89 String fileName = file.getName(); 90 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));//獲取輸入流 91 HSSFWorkbook wk = new HSSFWorkbook(bis); // poi提供的類 工作簿 92 HSSFSheet sheet = wk.getSheetAt(0);//獲取一片? 工作表 93 HSSFCell cell = null; 94 for(int rowIndex=startRow; rowIndex<=sheet.getLastRowNum(); rowIndex++){ //getLastRowNum 獲取最後一行的行號 95 HSSFRow row = sheet.getRow(rowIndex); //獲取行數據 96 if(null==row){ //如果這行數據爲空 繼續 97 continue; 98 } 99 RowData rowData = new RowData(rowIndex+1);//起始是2 行數據存儲對象初始化 100 List<CellData> cells = new ArrayList<CellData>();// 單元格s 對象存儲對象初始化 101 for(int columnIndex=0; columnIndex<columnKey.length; columnIndex++){ // 列個數 102 String key = columnKey[columnIndex]; 103 String cellValue = ""; 104 cell = row.getCell(columnIndex); //獲取獨立單元格對象 105 if(null!=cell){ 106 cell.setCellType(Cell.CELL_TYPE_STRING);//設置對象數據類型爲String 107 cellValue = cell.getStringCellValue(); // 獲取數據 是String 因爲上面轉換了 108 } 109 if(!StringUtil.isBlank(cellValue)){ 110 cellValue = cellValue.trim(); //非空進行剪切 111 } 112 CellData cellData = new CellData(columnIndex+1, cellValue, key);//單元格數據對象實例化 參數有: 的列的位置 值 對應的列明 113 cells.add(cellData); //添加到單元格s對象中去 114 } 115 rowData.setCells(cells); // 行數據添加 cells 值 116 rows.add(rowData); // 行數據列表 添加 行數據 117 } 118 //關閉輸入流 119 bis.close(); 120 } catch (Exception e) { 121 e.printStackTrace(); 122 } 123 return rows; //rows 可以說是 內存中的轉化好的表格格式正確文件內容對象 124 } 125 126 /** 127 * 解析2007 excel文件 128 * @param file excel文件 129 * @param startRow 起始行 0爲第一行 130 * @param columnKey 每列對應的key值 131 * @return 132 */ 133 private static List<RowData> parse2007Excel(File file, int startRow, String[] columnKey){ 134 List<RowData> rows = new ArrayList<RowData>(); 135 try { 136 String fileName = file.getName(); 137 BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); 138 XSSFWorkbook wb = new XSSFWorkbook(in); 139 XSSFSheet sheet = wb.getSheetAt(0); 140 XSSFCell cell = null; 141 for(int rowIndex=startRow; rowIndex<=sheet.getLastRowNum(); rowIndex++) { 142 XSSFRow row = sheet.getRow(rowIndex); 143 if(null==row){ 144 continue; 145 } 146 RowData rowData = new RowData(rowIndex+1); 147 List<CellData> cells = new ArrayList<CellData>(); 148 for(int columnIndex=0; columnIndex<columnKey.length; columnIndex++){ 149 String key = columnKey[columnIndex]; 150 String cellValue = ""; 151 cell = row.getCell(columnIndex); 152 cell.setCellType(Cell.CELL_TYPE_STRING); 153 cellValue = cell.getStringCellValue(); 154 if(!StringUtil.isBlank(cellValue)){ 155 cellValue = cellValue.trim(); 156 } 157 158 CellData cellData = new CellData(columnIndex+1, cellValue, key); 159 cells.add(cellData); 160 } 161 rowData.setCells(cells); 162 rows.add(rowData); 163 } 164 //關閉輸入流 165 in.close(); 166 } catch (Exception e) { 167 e.printStackTrace(); 168 } 169 return rows; 170 } 171 }
1 public class Validator { 2 3 4 /*public static void main(String[] args) { 5 String mobile = "18412312313"; 6 String phone = "010-12312312"; 7 String username = "fdsdfsdj"; 8 System.out.println(Validator.isUsername(username)); 9 System.out.println(Validator.isChinese(username)); 10 11 String email = "[email protected]"; 12 System.out.println("isMobile="+Validator.isMobile(mobile)); 13 System.out.println("isPhone="+Validator.isPhone(phone)); 14 String regex = "^zo+$"; 15 String str = "zozo"; 16 boolean flag = Validator.testString(regex, str); 17 System.out.println(flag); 18 } 19 20 */ 21 public static boolean testString(String regex, String str){ 22 return Pattern.matches(regex, str); 23 } 24 25 26 /** 27 * 正則表達式:驗證用戶名 28 */ 29 public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,17}$"; 30 31 /** 32 * 正則表達式:驗證密碼 33 */ 34 public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,16}$"; 35 36 /** 37 * 正則表達式:驗證手機號 38 */ 39 public static final String REGEX_MOBILE = "^((13[0-9])|(14[0-9])|(15[0-9])|(18[0-9])|(17[0-9]))\\d{8}$"; 40 41 /** 42 * 正則表達式:驗證固話 43 */ 44 public static final String REGEX_PHONE = "^(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})|(0\\d{3}-\\d{8})$"; 45 46 /** 47 * 正則表達式:驗證qq 48 */ 49 public static final String REGEX_QQ = "^[1-9][0-9]{4,} $"; 50 51 /** 52 * 正則表達式:驗證郵箱 53 */ 54 public static final String REGEX_EMAIL = "^[A-Za-z0-9][\\w\\-\\.]{1,12}@([\\w\\\\-]+\\.)+[\\w]{2,3}$"; 55 56 /** 57 * 正則表達式:驗證漢字 58 */ 59 public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5],{0,}$"; 60 61 /** 62 * 正則表達式:驗證身份證 63 */ 64 public static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)"; 65 66 /** 67 * 正則表達式:驗證URL 68 */ 69 // public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"; 70 71 /** 72 * 正則表達式:驗證IP地址 73 */ 74 public static final String REGEX_IP_ADDR = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"; 75 76 /** 77 * 校驗用戶名 78 * 79 * @param username 80 * @return 校驗通過返回true,否則返回false 81 */ 82 public static boolean isUsername(String username) { 83 return Pattern.matches(REGEX_USERNAME, username); 84 } 85 86 /** 87 * 校驗密碼 88 * 89 * @param password 90 * @return 校驗通過返回true,否則返回false 91 */ 92 public static boolean isPassword(String password) { 93 return Pattern.matches(REGEX_PASSWORD, password); 94 } 95 96 /** 97 * 校驗手機號 98 * 99 * @param mobile 100 * @return 校驗通過返回true,否則返回false 101 */ 102 public static boolean isMobile(String mobile) { 103 return Pattern.matches(REGEX_MOBILE, mobile); 104 } 105 106 /** 107 * 校驗郵箱 108 * 109 * @param email 110 * @return 校驗通過返回true,否則返回false 111 */ 112 public static boolean isEmail(String email) { 113 return Pattern.matches(REGEX_EMAIL, email); 114 } 115 116 /** 117 * 校驗固話 118 * @param phone 119 * @return 120 */ 121 public static boolean isPhone(String phone){ 122 return Pattern.matches(REGEX_PHONE, phone); 123 } 124 125 /** 126 * 校驗qq 127 * @param qq 128 * @return 129 */ 130 public static boolean isQQ(String qq){ 131 return Pattern.matches(REGEX_QQ, qq); 132 } 133 134 /** 135 * 校驗漢字 136 * 137 * @param chinese 138 * @return 校驗通過返回true,否則返回false 139 */ 140 public static boolean isChinese(String chinese) { 141 return Pattern.matches(REGEX_CHINESE, chinese); 142 } 143 144 /** 145 * 校驗身份證 146 * 147 * @param idCard 148 * @return 校驗通過返回true,否則返回false 149 */ 150 public static boolean isIDCard(String idCard) { 151 return Pattern.matches(REGEX_ID_CARD, idCard); 152 } 153 154 /** 155 * 校驗URL 156 * 157 * @param url 158 * @return 校驗通過返回true,否則返回false 159 */ 160 // public static boolean isUrl(String url) { 161 // return Pattern.matches(REGEX_URL, url); 162 // } 163 164 /** 165 * 校驗IP地址 166 * 167 * @param ipAddr 168 * @return 169 */ 170 public static boolean isIPAddr(String ipAddr) { 171 return Pattern.matches(REGEX_IP_ADDR, ipAddr); 172 } 173 174 175 176 }
======================
SpringMVC文件上傳 Excle文件 Poi解析並批量導入 MYSQL數據庫
/**
* 業務需求說明:
* 1 批量導入成員 並且 自主創建賬號
* 2 校驗數據格式 且 重複導入提示 已被佔用
* 3 導入手機相同 則更新源有信息
* 4 返回錯誤信息
*/
jsp文件 部分 瀏覽 以及功能鍵 代碼:
1 <div class="modal-body" style="position: relative;"> 2 <form class="" role="form" id="upload_form"> 3 <select class="form-control m-b" id="upload_dept" name="uploadDept"> 4 </select> 5 <div class="input-group"> 6 <input type="text" class="form-control input-sm" name="upload_filename"> 7 <div class="input-group-btn"> 8 <button type="button" class="btn btn-sm btn-primary"> 9 瀏覽 10 </button> 11 </div> 12 </div> 13 <!-- 選擇上傳文件按鈕 type類型指定爲 file accept 可以在瀏覽過程中 進行過濾顯示 支持多個用逗號隔開 --> 14 <!-- 選擇文件後顯示文件名稱 對更改事件綁定了事件監聽器 selectUploadFile(this) 此框按鈕id爲: upload_file --> 15 <input type="file" id="upload_file" onchange="selectUploadFile(this)" name="uploadFile" accept=".xls,.xlsx" class="input-fzliulan"> 16 </form> 17 </div> 18 <div class="modal-footer"> 19 <button type="button" id="btn_upCancel" class="btn btn-white" data-dismiss="modal">關閉</button> 20 <button type="button" id="btn_upSubmit" class="btn btn-success pdlr16"><span id="uploadTxt">導入</span><img id="loadingImg" style="display: none" src="<%=contextPath%>/resource/images/loading.gif" /></button> 21 </div>
comm.jsp文件定義的變量:
1 var userId = '<c:out value="${sessionScope.USER.userId}" />'; 2 var orgId = '<c:out value="${sessionScope.ORG.orgId}" />'; 3 var authLevel = '<c:out value="${sessionScope.USER.authLevel}" />'; 4 var userType = '<c:out value="${sessionScope.USER.type}" />'; 5 var orgAmount= '<c:out value="${sessionScope.AGENT.orgAmount}" />'; 6 var loginUser = {userId: userId, orgId: orgId, authLevel: authLevel, type: userType ,orgAmount:orgAmount};
頁面js:
1 $(function(){ 2 bindEvent(); 3 }) 4 /** 爲頁面按鈕綁定事件 5 */ 6 function bindEvent(){ 7 /** 8 * 顯示上傳文件名稱 9 * @param fileObj 10 */ 11 function selectUploadFile(fileObj){ 12 var fullPath = $(fileObj).val(); 13 var index = fullPath.lastIndexOf('\\') + 1; 14 var fileName = fullPath.substring(index); 15 $('input[name="upload_filename"]').val(fileName); 16 } 17 18 19 20 $('#downLoadTemplate').click(function(){ //下載模板按鈕的監聽器 21 var url = webContext + '/file\\template\\組織用戶信息模板.xlsx'; 22 downloadFile(url) 23 }); 24 25 /** 26 * 上傳文件 27 */ 28 29 $('#btn_upSubmit').click(function(){ 30 var valid = uploadValidator.checkForm(); //檢測傳單內容輸入是否有問題 31 if(!valid){ 32 uploadValidator.showErrors(); 33 } else{ //檢測成功 34 $('#uploadTxt').text(''); 35 $('#loadingImg').show(); //按鈕換成動畫效果圖片 36 /** 準備參數: */ 37 var orgId = loginUser.orgId; //但錢用戶的組織id 38 var deptId = $('#upload_dept').val(); // 選框中選擇的部門id 39 var password = hex_md5('123456');// 默認密碼 進行加密 40 var param = {orgId: orgId, deptId: deptId, password: password}; //ajax傳輸 攜帶json詳細信息 41 var url = webContext + '/org/uploadOrgUser'; // /** 使用ajaxFileUpload */ 42 $.ajaxFileUpload({ 43 url: url, //用於文件上傳的服務器端請求地址 44 secureuri: false, //是否需要安全協議,一般設置爲false 45 fileElementId: 'upload_file', //文件上傳域的ID 就是選定文件的 type=file的input框的id ajaxFileUpload 會幫我們把他分裝到ajax請求的 攜帶對象域中去 46 dataType: 'json', //返回值類型 一般設置爲json 47 type: 'post', 48 data: param, 49 success:function(){ 50 //成功的success 回調方法等業務流程結束後再寫 51 //先留已空白 52 } 53 }) 54 } 55 }) 56 }
項目使用SpringMVC :
其controller爲:
1 //-----------------------------------MVC 的控制器---------------------- 2 //Controller爲: 3 @Controller 4 @RequestMapping("/org") 5 public class OrgController extends BaseController { 6 7 @Autowired 8 private IOrgService orgService; 9 10 @RequestMapping("/uploadOrgUser") 11 @ResponseBody 12 public Map<String, Object> uploadOrgUser(HttpServletRequest request){ 13 Map<String, Object> map = new HashMap<String, Object>(); 14 String flag = "failure"; 15 String msg = "上傳成功"; 16 MultipartHttpServletRequest mtRequest = (MultipartHttpServletRequest) request;//多部分httpRquest對象 是HttpServletRequest類的一個子類接口 支持文件分段上傳對象 17 Integer orgId = RequestUtil.getIntParam(mtRequest, "orgId"); //組織id 18 Integer deptId = RequestUtil.getIntParam(mtRequest, "deptId"); //選取部門id 19 String password = RequestUtil.getStringParam(request, "password"); // 初始密碼 已被md5加密 20 MultipartFile upFile = mtRequest.getFile("uploadFile"); // 直接獲取文件對象 21 if(null == upFile || upFile.getSize()==0){ //文件不存在的情況 22 msg = "上傳文件不存在或爲空文件"; 23 map.put("flag", flag); 24 map.put("msg", msg); 25 return map; //返回錯誤信息 26 } 27 String targetPath = request.getServletContext().getRealPath("/file/upload"); //獲取服務器 中file/update 的 url地址 28 map = orgService.uploadOrgUser(targetPath, orgId, deptId, password, upFile); //調用實現類 返回 界面消息 對象 29 return map; 30 } 31 }
--業務層接口--說明:
1 public interface IOrgService { 2 /** 3 * @param targetPath 4 * @param orgId 5 * @param deptId 6 * @param password 7 * @param upFile 8 * @return 9 */ 10 public Map<String, Object> uploadOrgUser(String targetPath, Integer orgId, Integer deptId, String password, MultipartFile upFile); 11 }
--業務層實現類:
1 //業務層實現類: 2 @Service("orgService") 3 public class OrgServiceImpl extends BaseService implements IOrgService { 4 5 @Autowired 6 private IOrgDao orgDao; 7 8 @Autowired 9 private IUserDao userDao; 10 11 @Autowired 12 private IDeptDao deptDao; 13 14 @Autowired 15 private IOrgUserDao orgUserDao; 16 17 @Autowired 18 private IServiceAuthDao authDao; 19 20 /** 批量導入 業務方法 **/ 21 public Map<String, Object> uploadOrgUser(String targetPath, Integer orgId, Integer deptId, String password, MultipartFile upFile) { 22 Map<String,Object> rm = new HashMap<String,Object>(); 23 String flag ="failure"; 24 String msg = "上傳失敗"; 25 File f = new File(targetPath) //實例硬盤中文件夾(路徑)對象 26 if(!f.exists()){//判斷此路徑/文件夾是否存在 27 f.mkdirs(); //如果不存在 則創建文件夾/目錄 28 } 29 String originalName = upFile.getOriginalFilename();//獲取文件對象原始文件名 30 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 31 String tag = sdf.format(new Date()); 32 String upFileName = targetPath + File.separator+tag+"_"+originalName;// 拼接出文件的要存儲的位置(全路徑) 33 File file = new File(upFileName);//創建 內存中的File對象 34 if(file.exists()){ //判斷是否存在 35 file.delete();//如果有重名文件存在 就刪除文件 36 // 這個對象對應的硬盤必須刪 不能存在 如果已經存在 則會拋出 37 // IOException異常 38 } 39 List<OrgUser> orgUsers = null; 40 List<User> users = null; 41 List<RowData> offedData = null; //List 集合對象準備 42 try{ 43 upFile.transferTo(file);//轉存文件 寫入硬盤 //這個 本質還是一樣的打開流傳文件 需要注意 file對應的硬盤中的文件不能存在 需要刪除 否則會拋出 文件已經存在且不能刪除 異常 44 // 校驗上傳數據 45 /** 輔助方法一 **/ 46 Map<String,Object> validData = validUpload(file,orgId,deptId);// 校驗數據 分類 返回 map形式 47 users = (List<User>) validData.get("PASSED_USERS"); //通過的user 是向 m_user 表的 48 orgUsers = (List<OrgUser>) validData.get("PASSED_ORGUSERS"); // 是向 m_org_user 表的 49 offedData = (List<RowData>) validData.get("OFFED_ROW"); //? 50 int rowNum = (Integer) validData.get("DATA_SIZE"); // excle 數據總長度 51 rm.put("ROW_COUNT", rowNum);//業務類的總長度 52 53 List<OrgUser> ous = orgUserDao.getOrgUsers(orgId);//獲取組織的所有用戶 54 ServiceAuth sa = new ServiceAuth(); //權限對象 55 sa.setOrgId(orgId); // 設置組織id 56 sa.setServiceCode(Sys.GROUP_ORG); //設置服務編碼 多用戶版基礎服務 57 sa.setType(Sys.TYPE_BUY); //設置 類型 爲購買類型 58 ServiceAuth nSa = authDao.getOrgServiceAuthInfo(sa); //獲取組織服務等級 詳細信息 59 int actSize = ous.size(); // 當前組織已有用戶的總長度 60 int license = nSa.getLicense(); // 組織上限人數 61 int totalNum = 0; //設置總數爲 0 62 63 Org o = orgDao.getOrgById(orgId); //獲取組織對象 64 Date duration = DateFormater.stringToDate(o.getDuration(), "yyyy-MM-dd"); //獲取服務到期時間 65 //上數據庫插入數據 66 if(null!=users && !users.isEmpty()){ 67 totalNum = actSize + users.size(); //總數現在等於 添加人數和已有人數 68 if(totalNum < license){//上傳人數和原有人數之和小於組織服務人數上限 69 for(int i=0; i<users.size(); i++){ 70 User u = users.get(i); 71 u.setPassword(password); 72 OrgUser ou = orgUsers.get(i); 73 userDao.addUser(u); 74 //添加到微信企業號 75 addCpUser(u); 76 //添加個人空間 77 Org selfOrg = new Org(); 78 selfOrg.setAdminName(u.getUserName()); 79 selfOrg.setType(Sys.ORG_TYPE_PER); 80 selfOrg.setState(Sys.ORG_VERIFY_1); 81 selfOrg.setAdminId(u.getUserId()); 82 selfOrg.setAdminName(u.getUserName()); 83 selfOrg.setDuration(duration); 84 selfOrg.setDel(Sys.UN_STOPED); 85 selfOrg.setCreateTime(new Date()); 86 selfOrg.setUpdateTime(new Date()); 87 selfOrg.setIdparent(0); 88 orgDao.addOrg(selfOrg); 89 Dept d = new Dept(); 90 d.setDeptId(0); 91 addOrgUserRelation(selfOrg, d, u); 92 if(null!=u.getUserId() && u.getUserName().equals(ou.getOrgUserName())){ 93 ou.setUserId(u.getUserId()); 94 orgUserDao.addOrgUser(ou); 95 } 96 } 97 rm.put("PASSED_COUNT", users.size());//成功數據 98 } else { 99 rm.put("ORG_LICENSE", license); //上限 100 rm.put("ORG_ACTSIZE", actSize); // 101 rm.put("OVER_LICENSE", totalNum - license); 102 } 103 104 } 105 int offedCount = 0; 106 if(null!= offedData && !offedData.isEmpty()){ 107 offedCount = offedData.size(); 108 rm.put("OFFED_DATA", offedData); 109 } 110 rm.put("OFFED_COUNT", offedCount); 111 112 flag = "success"; 113 msg = "上傳成功"; 114 } catch (Exception e2) { 115 logger.error("Exception while uploadOrgUser", e2); 116 } 117 rm.put("flag", flag); 118 rm.put("msg", msg); 119 120 return rm; 121 122 } 123 }
----------------------------------------------------------------------------------------------------------------------------------------------
//輔助方法清單:
1 //*************************** 輔助方法一 ***************************************************************** 2 /** 3 * 校驗上傳文件 4 * 參數:文件對象 5 * 組織id 6 * 部門id 7 */ 8 private Map<String, Object> validUpload(File uploadFile, Integer orgId, Integer deptId) throws Exception{ 9 Map<String, Object> map = new HashMap<String, Object>(); 10 List<User> passed = null; 11 List<User> offed = null; 12 List<String> mobileList = userDao.getAllActiveMobile();//爲了防止已註冊用戶再次註冊 13 List<String> emailList = userDao.getAllActiveEmail();// 現在還是查詢出所有的 ------需要優化標記 14 //獲取上傳的excel中的數據 15 //******輔助方法二********* 16 ExcelData uploaddata = getUploadUserData(uploadFile);//獲取內存中解析好的excle數據對象 17 //校驗上傳數據 18 //******輔助方法三********* 19 Map<String, Object> dataMap = validUploadData(orgId, deptId, uploaddata, mobileList, emailList); //返回的是數據對象 20 21 return dataMap; 22 }
//*************************** 輔助方法二 ***************************************************************** /** * 獲取上傳文件的數據 * @param uploadFile * @return * @throws Exception */ private ExcelData getUploadUserData(File uploadFile) throws Exception{ List<User> list = new ArrayList<User>(); String[] columnKey = {"userName", "mobile", "phone", "email", "QQ", "weixin", "job", "dept", "note"}; int startRow = 1; ExcelData uploadData = FileUtil.parseExcelFile(uploadFile, startRow, columnKey);//將要拋出異常 return uploadData; } }
1 //*************************** 輔助方法三 ***************************************************************** 2 /** 3 * 方法說明: 4 * 校驗上傳數據 5 * 6 * 7 * @param orgId 其應該所屬的組織 8 * @param deptId 所選的部門id 9 * @param excelData excel表格數據對象 10 * @param mobiles 所有的手機號碼 集合 用來判斷手機是否註冊 11 * @param emails 所有的郵箱號碼 集合 12 * @return 13 */ 14 private Map<String, Object> validUploadData(Integer orgId, Integer deptId,ExcelData excelData, List<String> mobiles, List<String> emails) { 15 Map<String, Object> map = new HashMap<String, Object>(); 16 List<RowData> passed = new ArrayList<RowData>(); 17 List<User> passedUsers = new ArrayList<User>(); // 通過驗證的 到 m_user 18 List<OrgUser> passedOrgUsers = new ArrayList<OrgUser>(); //通過驗證的 到m_org_user 19 List<RowData> offed = new ArrayList<RowData>(); 20 List<RowData> rows = null;// 所有數據 21 Date createTime = new Date();//創建時間 22 Date updateTime = new Date(); //更新時間 23 List<Dept> deptList = null; //當前組織的所有部門的 list集合 24 Map<String, Dept> deptMap = new HashMap<String, Dept>(); 25 if(null != excelData && null != excelData.getRows() && !excelData.getRows().isEmpty()){ //如果傳入對象不爲空 26 rows = excelData.getRows(); //獲取對象中的所有數據 類型應該是List集合 每個元素應該是一行數據 即:RowData 27 map.put("DATA_SIZE", rows.size());// 設置總數據有多少條 28 List<String> excelMobiles = new ArrayList<String>(); //用於存放excle表格中的電話號碼 29 List<String> excelEmails = new ArrayList<String>(); //用於存放excle表格中的郵箱號碼 30 deptList = deptDao.getDeptsByOrgId(orgId);//獲取所有部門? 31 for(Dept dept:deptList){ 32 String deptName = dept.getDeptName(); 33 deptMap.put(deptName, dept);//轉成map了 34 } 35 rowloop: //行循環跳出座標準備 36 for (int i = 0; i < rows.size(); i++) {//循環便利數據 37 OrgUser orgUser = new OrgUser(); //組織用戶 實例化對象準備 38 User user = new User(); //用戶 POJO準備 39 //獲取行數據 40 RowData r = rows.get(i); // 獲取行數據 41 int rowIndex = r.getRowIndex(); // 獲取當前行是第幾行 42 List<CellData> cells = r.getCells(); //獲取當前行的所有數據 cell 的s 43 boolean flag = true; 44 String userName="",mobile="",phone="",email="",qq="",weixin="",job=""; 45 int mIndex = 0; 46 int eIndex = 0; 47 columnloop: //列循環跳出座標準備 48 for (int j = 0; j < cells.size(); j++) { // 每一行單元格數據 遍歷 49 CellData c = cells.get(j); //獲取出當前的 數據獨立單元格 50 String key = c.getKey(); //屬於哪一列? 51 String cellValue = c.getCellValue(); //值 52 if("userName".equals(key)){ 53 userName = cellValue; 54 if(StringUtil.isBlank(cellValue)){ 55 flag = false; 56 c.setPassed(0); 57 c.setExtraInfo("用戶姓名不能爲空"); 58 continue columnloop; 59 } 60 user.setUserName(cellValue); 61 orgUser.setOrgUserName(cellValue); 62 } else if("mobile".equals(key)){ //手機相關驗證 63 mIndex = j; 64 mobile = cellValue; 65 if(!StringUtil.isBlank(cellValue)){ 66 if(!Validator.isMobile(cellValue)){ //校驗手機格式 67 flag = false; 68 c.setPassed(0); 69 c.setExtraInfo("不正確的手機號"); 70 continue columnloop; 71 } 72 73 if(mobiles.contains(cellValue.trim())){// 比對數據庫中的 是否已被註冊 74 flag = false; 75 c.setPassed(0); 76 c.setExtraInfo("該手機號已經被使用"); 77 continue columnloop; 78 } 79 if(excelMobiles.contains(cellValue.trim())){ // 當前表格 數據有重複 80 flag = false; 81 c.setPassed(0); 82 c.setExtraInfo("重複的手機號碼"); 83 continue columnloop; 84 } 85 user.setLoginName(cellValue); 86 } 87 user.setMobile(cellValue); 88 } else if("phone".equals(key)){ //暫無 89 phone = cellValue; 90 if(!StringUtil.isBlank(cellValue)){ 91 // if(!Validator.isPhone(cellValue)){ 92 // flag = false; 93 // c.setPassed(0); 94 // c.setExtraInfo("不正確的電話號"); 95 // continue columnloop; 96 // } 97 } 98 user.setPhone(cellValue); 99 } else if("email".equals(key)){ // 郵箱相關驗證 100 eIndex = j; 101 email = cellValue; 102 if(!StringUtil.isBlank(cellValue)){ 103 if(!Validator.isEmail(cellValue)){ 104 flag = false; 105 c.setPassed(0); 106 c.setExtraInfo("郵箱格式不正確"); 107 continue columnloop; 108 } 109 if(emails.contains(cellValue.trim())){ 110 flag = false; 111 c.setPassed(0); 112 c.setExtraInfo("該郵箱已經被使用"); 113 continue columnloop; 114 } 115 if(excelMobiles.contains(cellValue.trim())){ 116 flag = false; 117 c.setPassed(0); 118 c.setExtraInfo("重複的郵箱"); 119 continue columnloop; 120 } 121 user.setLoginName(cellValue); 122 } 123 user.setEmail(cellValue); 124 } else if("QQ".equals(key)){ 125 qq = cellValue; 126 user.setQq(cellValue); 127 } else if("weixin".equals(key)){ 128 weixin = cellValue; 129 user.setWeixin(cellValue); 130 } else if("job".equals(key)){ 131 job = cellValue; 132 orgUser.setPosition(cellValue); 133 //暫無 134 } else if("note".equals(key)){ 135 user.setNote(cellValue); 136 } else if("dept".equals(key)) { 137 if(!StringUtil.isBlank(cellValue) && null!=deptMap.get(cellValue.trim())){ 138 Dept d = deptMap.get(cellValue.trim()); 139 orgUser.setDeptId(d.getDeptId()); 140 } else { 141 orgUser.setDeptId(deptId); 142 } 143 } else { 144 //暫無 145 } 146 } 147 //校驗手機與郵箱是否同時爲空 148 if(StringUtil.isBlank(mobile) && StringUtil.isBlank(email)){ 149 flag = false; 150 CellData mobileCell = cells.get(mIndex);//所屬的 行和列 151 CellData emailCell = cells.get(eIndex); 152 mobileCell.setPassed(0); //設置是否通過了校驗的標識 注:此標識是對單元格數據進行設置的 153 mobileCell.setExtraInfo("手機與郵箱不能同時爲空"); //沒有通過校驗 進行 154 emailCell.setPassed(0); 155 emailCell.setExtraInfo("手機與郵箱不能同時爲空"); 156 } 157 if(flag){ //驗證通過的話 158 //初始化user 和 orgUser對象 159 user.setDefaultOrgId(orgId); 160 user.setMultiLogin(0); 161 user.setIsDistributor(0); 162 user.setSrcOrg(orgId); 163 user.setMobileBinded(0); 164 user.setEmailBinded(0); 165 user.setUtype(0); 166 user.setUpdateTime(updateTime); 167 user.setCreateTime(createTime); 168 user.setDel(Sys.UN_STOPED); 169 user.setType(2); 170 user.setSource(1); 171 user.setIspremiumuser(true); 172 // user.setNote("上傳生成用戶"); 173 user.setPassword("123456"); 174 175 orgUser.setOrgId(orgId); 176 // orgUser.setDeptId(deptId); 177 orgUser.setCreateTime(createTime); 178 orgUser.setUpdateTime(updateTime); 179 orgUser.setDel(Sys.UN_STOPED); 180 orgUser.setState(1); 181 orgUser.setIsDataCommissioner(0); 182 orgUser.setIsMarketCommissioner(0); 183 //向通過list裏添加數據 184 passedUsers.add(user); //添加到通過的 數據列表中去 185 passedOrgUsers.add(orgUser); 186 if(!StringUtil.isBlank(mobile)){ 187 excelMobiles.add(mobile); //添加到 準備的 list中去 以防下面重複數據 在上面驗證 188 } 189 if(!StringUtil.isBlank(email)){ 190 excelEmails.add(email); 191 } 192 } else { 193 offed.add(r); 194 } 195 196 } 197 } 198 map.put("PASSED_USERS", passedUsers); // 199 map.put("PASSED_ORGUSERS", passedOrgUsers); 200 map.put("OFFED_ROW", offed); 201 return map; 202 }
==============================================================================================
// 輔助工具類:
1 package com.SS.util; 2 3 import com.SS.util.excel.CellData; 4 import com.SS.util.excel.ExcelData; 5 import com.SS.util.excel.RowData; 6 import com.sun.image.codec.jpeg.JPEGCodec; 7 import com.sun.image.codec.jpeg.JPEGEncodeParam; 8 import com.sun.image.codec.jpeg.JPEGImageEncoder; 9 import org.apache.log4j.Logger; 10 import org.apache.poi.hssf.usermodel.HSSFCell; 11 import org.apache.poi.hssf.usermodel.HSSFRow; 12 import org.apache.poi.hssf.usermodel.HSSFSheet; 13 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 14 import org.apache.poi.ss.usermodel.Cell; 15 import org.apache.poi.xssf.usermodel.XSSFCell; 16 import org.apache.poi.xssf.usermodel.XSSFRow; 17 import org.apache.poi.xssf.usermodel.XSSFSheet; 18 import org.apache.poi.xssf.usermodel.XSSFWorkbook; 19 20 import javax.imageio.ImageIO; 21 import java.awt.*; 22 import java.awt.image.BufferedImage; 23 import java.io.*; 24 import java.util.ArrayList; 25 import java.util.List; 26 27 /** 28 * 文件操作工具類 29 */ 30 public class FileUtil { 31 32 private Logger logger = Logger.getLogger(FileUtil.class); 33 34 /** 35 * 獲取文件的後綴名稱 36 * @param file 37 * @return 38 */ 39 public static String getFileSuffix(File file){ 40 String suffix = ""; 41 if(null != file && StringUtil.isBlank(file.getName())){ 42 String fileName = file.getName(); 43 suffix = fileName.substring(fileName.lastIndexOf(".")); 44 } 45 46 return suffix; 47 } 48 49 /** 50 * 解析excel文件 51 * @param file excel文件 52 * @param startRow 起始行 0爲第一行 53 * @param columnKey 每列對應的key值 54 * @return 55 */ 56 public static ExcelData parseExcelFile(File file, int startRow, String[] columnKey){ 57 List<RowData> rows = null; 58 ExcelData excelData = new ExcelData(); 59 try { 60 if(null==file || !file.exists() || columnKey.length<1){ 61 return excelData; 62 } 63 String fileName = file.getName(); 64 excelData.setFileName(fileName); 65 if(fileName.endsWith("xls")){ 66 rows = parse2003Excel(file, startRow, columnKey); 67 } else if(fileName.endsWith("xlsx")){ 68 rows = parse2007Excel(file, startRow, columnKey); 69 } else { 70 throw new RuntimeException("Unknown file type : "+fileName); 71 } 72 excelData.setRows(rows); 73 } catch (Exception e) { 74 e.printStackTrace(); 75 } 76 return excelData; 77 } 78 79 /** 80 * 解析2003 excel文件 81 * @param file excel文件 82 * @param startRow 起始行 0爲第一行 第一行已經有 頭了 83 * @param columnKey 每列對應的key值 84 * @return 85 */ 86 private static List<RowData> parse2003Excel(File file, int startRow, String[] columnKey){ 87 List<RowData> rows = new ArrayList<RowData>(); 88 try { 89 String fileName = file.getName(); 90 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));//獲取輸入流 91 HSSFWorkbook wk = new HSSFWorkbook(bis); // poi提供的類 工作簿 92 HSSFSheet sheet = wk.getSheetAt(0);//獲取一片? 工作表 93 HSSFCell cell = null; 94 for(int rowIndex=startRow; rowIndex<=sheet.getLastRowNum(); rowIndex++){ //getLastRowNum 獲取最後一行的行號 95 HSSFRow row = sheet.getRow(rowIndex); //獲取行數據 96 if(null==row){ //如果這行數據爲空 繼續 97 continue; 98 } 99 RowData rowData = new RowData(rowIndex+1);//起始是2 行數據存儲對象初始化 100 List<CellData> cells = new ArrayList<CellData>();// 單元格s 對象存儲對象初始化 101 for(int columnIndex=0; columnIndex<columnKey.length; columnIndex++){ // 列個數 102 String key = columnKey[columnIndex]; 103 String cellValue = ""; 104 cell = row.getCell(columnIndex); //獲取獨立單元格對象 105 if(null!=cell){ 106 cell.setCellType(Cell.CELL_TYPE_STRING);//設置對象數據類型爲String 107 cellValue = cell.getStringCellValue(); // 獲取數據 是String 因爲上面轉換了 108 } 109 if(!StringUtil.isBlank(cellValue)){ 110 cellValue = cellValue.trim(); //非空進行剪切 111 } 112 CellData cellData = new CellData(columnIndex+1, cellValue, key);//單元格數據對象實例化 參數有: 的列的位置 值 對應的列明 113 cells.add(cellData); //添加到單元格s對象中去 114 } 115 rowData.setCells(cells); // 行數據添加 cells 值 116 rows.add(rowData); // 行數據列表 添加 行數據 117 } 118 //關閉輸入流 119 bis.close(); 120 } catch (Exception e) { 121 e.printStackTrace(); 122 } 123 return rows; //rows 可以說是 內存中的轉化好的表格格式正確文件內容對象 124 } 125 126 /** 127 * 解析2007 excel文件 128 * @param file excel文件 129 * @param startRow 起始行 0爲第一行 130 * @param columnKey 每列對應的key值 131 * @return 132 */ 133 private static List<RowData> parse2007Excel(File file, int startRow, String[] columnKey){ 134 List<RowData> rows = new ArrayList<RowData>(); 135 try { 136 String fileName = file.getName(); 137 BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); 138 XSSFWorkbook wb = new XSSFWorkbook(in); 139 XSSFSheet sheet = wb.getSheetAt(0); 140 XSSFCell cell = null; 141 for(int rowIndex=startRow; rowIndex<=sheet.getLastRowNum(); rowIndex++) { 142 XSSFRow row = sheet.getRow(rowIndex); 143 if(null==row){ 144 continue; 145 } 146 RowData rowData = new RowData(rowIndex+1); 147 List<CellData> cells = new ArrayList<CellData>(); 148 for(int columnIndex=0; columnIndex<columnKey.length; columnIndex++){ 149 String key = columnKey[columnIndex]; 150 String cellValue = ""; 151 cell = row.getCell(columnIndex); 152 cell.setCellType(Cell.CELL_TYPE_STRING); 153 cellValue = cell.getStringCellValue(); 154 if(!StringUtil.isBlank(cellValue)){ 155 cellValue = cellValue.trim(); 156 } 157 158 CellData cellData = new CellData(columnIndex+1, cellValue, key); 159 cells.add(cellData); 160 } 161 rowData.setCells(cells); 162 rows.add(rowData); 163 } 164 //關閉輸入流 165 in.close(); 166 } catch (Exception e) { 167 e.printStackTrace(); 168 } 169 return rows; 170 } 171 }
1 public class Validator { 2 3 4 /*public static void main(String[] args) { 5 String mobile = "18412312313"; 6 String phone = "010-12312312"; 7 String username = "fdsdfsdj"; 8 System.out.println(Validator.isUsername(username)); 9 System.out.println(Validator.isChinese(username)); 10 11 String email = "[email protected]"; 12 System.out.println("isMobile="+Validator.isMobile(mobile)); 13 System.out.println("isPhone="+Validator.isPhone(phone)); 14 String regex = "^zo+$"; 15 String str = "zozo"; 16 boolean flag = Validator.testString(regex, str); 17 System.out.println(flag); 18 } 19 20 */ 21 public static boolean testString(String regex, String str){ 22 return Pattern.matches(regex, str); 23 } 24 25 26 /** 27 * 正則表達式:驗證用戶名 28 */ 29 public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,17}$"; 30 31 /** 32 * 正則表達式:驗證密碼 33 */ 34 public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,16}$"; 35 36 /** 37 * 正則表達式:驗證手機號 38 */ 39 public static final String REGEX_MOBILE = "^((13[0-9])|(14[0-9])|(15[0-9])|(18[0-9])|(17[0-9]))\\d{8}$"; 40 41 /** 42 * 正則表達式:驗證固話 43 */ 44 public static final String REGEX_PHONE = "^(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})|(0\\d{3}-\\d{8})$"; 45 46 /** 47 * 正則表達式:驗證qq 48 */ 49 public static final String REGEX_QQ = "^[1-9][0-9]{4,} $"; 50 51 /** 52 * 正則表達式:驗證郵箱 53 */ 54 public static final String REGEX_EMAIL = "^[A-Za-z0-9][\\w\\-\\.]{1,12}@([\\w\\\\-]+\\.)+[\\w]{2,3}$"; 55 56 /** 57 * 正則表達式:驗證漢字 58 */ 59 public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5],{0,}$"; 60 61 /** 62 * 正則表達式:驗證身份證 63 */ 64 public static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)"; 65 66 /** 67 * 正則表達式:驗證URL 68 */ 69 // public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"; 70 71 /** 72 * 正則表達式:驗證IP地址 73 */ 74 public static final String REGEX_IP_ADDR = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"; 75 76 /** 77 * 校驗用戶名 78 * 79 * @param username 80 * @return 校驗通過返回true,否則返回false 81 */ 82 public static boolean isUsername(String username) { 83 return Pattern.matches(REGEX_USERNAME, username); 84 } 85 86 /** 87 * 校驗密碼 88 * 89 * @param password 90 * @return 校驗通過返回true,否則返回false 91 */ 92 public static boolean isPassword(String password) { 93 return Pattern.matches(REGEX_PASSWORD, password); 94 } 95 96 /** 97 * 校驗手機號 98 * 99 * @param mobile 100 * @return 校驗通過返回true,否則返回false 101 */ 102 public static boolean isMobile(String mobile) { 103 return Pattern.matches(REGEX_MOBILE, mobile); 104 } 105 106 /** 107 * 校驗郵箱 108 * 109 * @param email 110 * @return 校驗通過返回true,否則返回false 111 */ 112 public static boolean isEmail(String email) { 113 return Pattern.matches(REGEX_EMAIL, email); 114 } 115 116 /** 117 * 校驗固話 118 * @param phone 119 * @return 120 */ 121 public static boolean isPhone(String phone){ 122 return Pattern.matches(REGEX_PHONE, phone); 123 } 124 125 /** 126 * 校驗qq 127 * @param qq 128 * @return 129 */ 130 public static boolean isQQ(String qq){ 131 return Pattern.matches(REGEX_QQ, qq); 132 } 133 134 /** 135 * 校驗漢字 136 * 137 * @param chinese 138 * @return 校驗通過返回true,否則返回false 139 */ 140 public static boolean isChinese(String chinese) { 141 return Pattern.matches(REGEX_CHINESE, chinese); 142 } 143 144 /** 145 * 校驗身份證 146 * 147 * @param idCard 148 * @return 校驗通過返回true,否則返回false 149 */ 150 public static boolean isIDCard(String idCard) { 151 return Pattern.matches(REGEX_ID_CARD, idCard); 152 } 153 154 /** 155 * 校驗URL 156 * 157 * @param url 158 * @return 校驗通過返回true,否則返回false 159 */ 160 // public static boolean isUrl(String url) { 161 // return Pattern.matches(REGEX_URL, url); 162 // } 163 164 /** 165 * 校驗IP地址 166 * 167 * @param ipAddr 168 * @return 169 */ 170 public static boolean isIPAddr(String ipAddr) { 171 return Pattern.matches(REGEX_IP_ADDR, ipAddr); 172 } 173 174 175 176 }
======================