java实现导入excel功能

实现功能:

  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="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="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="720px;border- 0.3px;margin-left:-10px;">
14                         <button id="tiJiao" type="button" class="czbtn" style="100px;font-size: 16px;">导入</button>
15                     </td>
16                 </tr>
17                 </table>
18             </form>
View Code

二、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         })
View Code

三、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 + "	");
 50                                     }else{
 51                                         System.out.print("该项不能为空" + "	");
 52                                         temp = false;
 53                                         //给Excel中为空格的必填项添加背景色
 54                                         Cell newCell = row.createCell(l);
 55                                         newCell.setCellStyle(style);
 56                                     }
 57                                 }else{//身份证号和工作背景
 58                                     System.out.print(cell + "	");
 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     }
View Code
原文地址:https://www.cnblogs.com/jichuang/p/8032883.html