實現功能:
1、Excel模板下載
2、導入excel
一、jsp效果和代碼

1 <form id="uploadForm" target="frameFile" class="bs-docs-example form-horizontal" method="post" action="<%=path %>/webCenter.do" enctype="multipart/form-data"> 2 <input type="hidden" id="conId" name="conId" value="<%=conId%>"> 3 <input type="hidden" id="code" name="code" value="<%=code%>"> 4 <input type="hidden" name="method" value="insertUserInfo"> 5 <table cellpadding="0" cellspacing="0" border="0" style="width:600px;margin:20px auto;text-algin:left;"> 6 <tr><td colspan="4"><input id="dyId" type="hidden"/></td></tr> 7 <tr><td colspan="3"><a href="/center/file/userInfoModel.xlsx" id="downloadModel" name="downloadModel" style="margin-left:7px;"><u>點擊下載人員模板</u></a></td></tr> 8 <tr><td colspan="4"><br/></td></tr> 9 <tr><td colspan="3"><input id="files" name="files" type="file" style="width:200px;"/></td></tr><!-- background:url('/center/images/uploadImg.png') no-repeat 0px 10px; --> 10 <tr><td colspan="4"><br/></td></tr> 11 <tr> 12 <td colspan="4" style="text-align: center;"> 13 <hr style="width:720px;border-width: 0.3px;margin-left:-10px;"> 14 <button id="tiJiao" type="button" class="czbtn" style="width:100px;font-size: 16px;">導入</button> 15 </td> 16 </tr> 17 </table> 18 </form>
二、js代碼

1 $("#tiJiao").click(function(){ 2 if($("#files").val() == ""){ 3 alert("請選擇要上傳的文件"); 4 }else{ 5 CommonPerson.Base.LoadingPic.FullScreenShow(); 6 $("#tkDiv").hide(); 7 $("#tk1").hide(); 8 $("#uploadForm").submit(); 9 } 10 })
三、action處理

1 /** 2 * 人員信息導入 3 * @param conId 4 * @param code 5 * @param request 6 * @param response 7 */ 8 @RequestMapping(params="method=insertUserInfo",method=RequestMethod.POST) 9 public void insertUserInfo(Integer conId,String code,HttpServletRequest request,HttpServletResponse response){ 10 try { 11 String msg = ""; 12 Integer state = 0; 13 String fileUrl = "/files/excel/"; 14 HttpSession session = this.getSession(request); 15 Adminuser adminUser = session.getAttribute("centerAdminUser") == null?null:(Adminuser) session.getAttribute("centerAdminUser"); 16 if(adminUser == null){ 17 try { 18 response.sendRedirect(request.getContextPath()+"/center/index.jsp"); 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 }else{ 23 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 24 MultipartFile multipartFile = multipartRequest.getFile("files"); 25 InputStream is = multipartFile.getInputStream(); 26 if(is!=null){ 27 Workbook wb = WorkbookFactory.create(is); 28 CellStyle style = wb.createCellStyle(); 29 style.setFillForegroundColor(IndexedColors.RED.getIndex()); 30 style.setFillPattern(CellStyle.SOLID_FOREGROUND); 31 List<UserInfo> userInfoList = new ArrayList<UserInfo>(); 32 int rowCount = 0; 33 boolean temp = true; 34 try { 35 Sheet st = wb.getSheetAt(0); 36 int rowNum = st.getLastRowNum(); //獲取Excel最后一行索引,從零開始,所以獲取到的是表中最后一行行數減一 37 int colNum = st.getRow(0).getLastCellNum();//獲取Excel列數 38 for(int r=1;r<=rowNum;r++){//讀取每一行,第一行為標題,從第二行開始 39 rowCount = r; 40 Row row = st.getRow(r); 41 UserInfo userInfo = new UserInfo(); 42 for(int l=0;l<colNum;l++){//讀取每一行的每一列 43 Cell cell = row.getCell(l); 44 if(cell != null){ 45 cell.setCellType(Cell.CELL_TYPE_STRING); 46 } 47 if(l != 8 && l != 9){//第9列和第10列(列數是從0開始遍歷)分別是身份證號碼和工作背景,這兩項為選填,其余項全為必填 48 if(cell != null && !"".equals(cell.toString().trim())){ 49 System.out.print(cell + "\t"); 50 }else{ 51 System.out.print("該項不能為空" + "\t"); 52 temp = false; 53 //給Excel中為空格的必填項添加背景色 54 Cell newCell = row.createCell(l); 55 newCell.setCellStyle(style); 56 } 57 }else{//身份證號和工作背景 58 System.out.print(cell + "\t"); 59 } 60 if(temp){ 61 switch (l) { 62 case 0: userInfo.setEmail(cell.getStringCellValue()); break; 63 case 1: userInfo.setMobilePhone(cell.getStringCellValue()); break; 64 case 2: userInfo.setPassword(cell.getStringCellValue()); break; 65 case 3: userInfo.setTrueName(cell.getStringCellValue()); break; 66 case 4: userInfo.setXingPingyin(cell.getStringCellValue()); break; 67 case 5: userInfo.setMingPingyin(cell.getStringCellValue()); break; 68 case 6: userInfo.setSex(cell.getStringCellValue()); break; 69 case 7: userInfo.setBirthday(cell.getStringCellValue()); break; 70 case 8: userInfo.setIdCard(cell.getStringCellValue()); break; 71 case 9: userInfo.setBeijin(cell.getStringCellValue()); break; 72 case 10: userInfo.setXueli(cell.getStringCellValue()); break; 73 case 11: 74 userInfo.setProvinceName(cell.getStringCellValue()); 75 Hospital provinceId = hospitalService.getHospitalByProvince(cell.getStringCellValue()); 76 if(provinceId != null){ 77 userInfo.setProvince(provinceId.getHospitalId()+""); 78 } 79 break; 80 case 12: 81 userInfo.setCityName(cell.getStringCellValue()); 82 Hospital cityId = hospitalService.getHospitalByCity(cell.getStringCellValue()); 83 if(cityId != null){ 84 userInfo.setCity(cityId.getHospitalId()+""); 85 } 86 break; 87 case 13: 88 userInfo.setDanwei(cell.getStringCellValue()); 89 break; 90 case 14: userInfo.setKs(cell.getStringCellValue()); break; 91 case 15: userInfo.setZhicheng(cell.getStringCellValue()); break; 92 case 16: userInfo.setZhiwei(cell.getStringCellValue()); break; 93 case 17: userInfo.setAddress(cell.getStringCellValue()); break; 94 case 18: userInfo.setZip(cell.getStringCellValue()); break; 95 case 19: userInfo.setTelphone(cell.getStringCellValue()); break; 96 } 97 userInfo.setConferencesId(conId); 98 userInfo.setFromWhere(code); 99 userInfo.setCreateTime(new Date()); 100 } 101 } 102 System.out.println(); 103 userInfoList.add(userInfo); 104 } 105 if(temp){//Excel完全沒有問題 106 webService.saveOrUpdateAll(userInfoList); 107 state = 1; 108 msg = "導入成功"; 109 }else{//Excel存在必填項為空的情況 110 state = 2; 111 msg = "Excel數據格式有問題,請下載表格,並將其中標紅色的部分填寫完整"; 112 String filePath = request.getSession().getServletContext().getRealPath("files/excel"); 113 String fileName = DateTime.getDateString(new Date(), "yyyy_MM_dd")+String.valueOf(System.currentTimeMillis()/1000)+".xlsx"; 114 OutputStream out = new FileOutputStream(new File(filePath + "/" + fileName)); 115 wb.write(out); 116 out.close(); 117 fileUrl = fileUrl + fileName; 118 } 119 }catch (Exception e) { 120 System.out.println("第"+rowCount+"行出錯"); 121 msg = "第"+rowCount+"行出錯"; 122 e.printStackTrace(); 123 } 124 } 125 is.close(); 126 JSONObject result = new JSONObject(); 127 result.accumulate("state",state); 128 result.accumulate("remark",msg); 129 result.accumulate("fileUrl",fileUrl); 130 String urlString = "<script type='text/javascript'>window.parent.insertResult('"+result.toString()+"')</script>"; 131 PrintWriter out = response.getWriter(); 132 response.setCharacterEncoding("utf-8"); 133 response.setContentType("text/html;charset=UTF-8"); 134 out.write(urlString); 135 out.flush(); 136 out.close(); 137 } 138 } catch (Exception e) { 139 e.printStackTrace(); 140 try { 141 JSONObject result = new JSONObject(); 142 result.accumulate("state",0); 143 result.accumulate("remark","excel數據格式有問題,導入失敗"); 144 String urlString ="<script type='text/javascript'>window.parent.insertResult('"+result.toString()+"')</script>"; 145 PrintWriter out = response.getWriter(); 146 response.setCharacterEncoding("utf-8"); 147 response.setContentType("text/html;charset=UTF-8"); 148 out.write(urlString); 149 out.flush(); 150 out.close(); 151 } catch (Exception e2) { 152 e2.printStackTrace(); 153 } 154 } 155 }