layui实现EXCEL文件导入的功能

layui实现EXCEL文件导入的功能

  1. 前台设置导出按钮。
<a href="javascript:;" class="layui-btn" lay-event="uploadFile" style="font-size:15px;"><span><i class="layui-icon" >&#xe67c;</i>导入</span></a>


<input type="file" style="display: none" id="file" name="file" onchange="uploadFile(this)"></input>

uploadFile:function () {
    $('#file').click();
 }

function uploadFile(file){
      //var clientid = $("#clientid").val();
      var fileName=$("#file").val();
      if(fileName == '') {
          layer.msg('请选择文件!',{

          });
          return false;
      }
      //验证文件格式
      var fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)).toLowerCase();
      if (fileType != 'xls') {
          layer.msg('文件格式不正确!');
          alert(fileType)
          return false;
      }
      //var index = layer.msg('正在上传,请稍候',{icon: 16,time:false,shade:0.8});
      $.ajaxFileUpload({
          url : "${base}/risen/zzgl/trade/importTradeBase.do", //用于文件上传的服务器端请求地址
          secureuri : false, //一般设置为false
          fileElementId : 'file', //文件上传空间的id属性  <input type="file" id="file" name="file" />
          type : 'post',
          dataType : 'text', //返回值类型 一般设置为
          async : true,
          success: function (res) {
              console.log(res);
              //var str=data.data.strList;
              // if (res == "SUCCESS") {
              layer.msg(res,function () {
                  window.location.reload();
              });
              // } else {
              //     layer.msg("导入失败");
              // }
          }

      });
      return false;
    }
  1. 后台controller层
 /**
     *   接受文件   解析  上传资料。
     *   /admin/client/upload_excel
     */
    @ResponseBody
    @RequestMapping("/importTradeBase")
    public Object importTradeBase(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request)throws Exception {
        JSONObject jsonObject = new JSONObject();
        //导入并返回结果,用json返回
        String msg = getRisenTradeBaseService().importTradeBase(file);
        //jsonObject.put("code", "0");
        jsonObject.put("msg", msg);
        //jsonObject.put("data", null);
        return jsonObject;
    }
  1. 后台service层
  /**
   * 科普教育基地导入
   * @param multipartFile
   * @return
   */
  String importTradeBase(MultipartFile multipartFile);

  @Override
  public String importTradeBase(MultipartFile multipartFile) {
      String msg = "";
      String clTime = "";
      int k = 0;
      Date date =null;
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      //原文件名
      String fileName = multipartFile.getOriginalFilename();
      // 文件扩展名
      String fileType = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
      try {
          FileInputStream fis = (FileInputStream) multipartFile.getInputStream();
          List<RisenTradeBase> list = new ArrayList<RisenTradeBase>();
          if(fileType.equals("xls")){
              HSSFWorkbook workbook = new HSSFWorkbook(fis);
              HSSFSheet sheet=workbook.getSheetAt(0);
              HSSFRow rowdata=null;
              for (int i = 2; i < sheet.getLastRowNum(); i++) {
                  RisenTradeBase risenTradeBase= new RisenTradeBase();
                  rowdata = sheet.getRow(i);
                  //rowdata.getCell(0).setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING);
                  rowdata.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(10).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(11).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(12).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(13).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(14).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(15).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(16).setCellType(Cell.CELL_TYPE_STRING);
                  rowdata.getCell(17).setCellType(Cell.CELL_TYPE_STRING);

                  String name = rowdata.getCell(1).getStringCellValue();//基地名称
                  String contacts = rowdata.getCell(2).getStringCellValue();//联系人
                  String phone = rowdata.getCell(3).getStringCellValue();//联系人办公电话
                  String fax = rowdata.getCell(4).getStringCellValue();//联系人传真号码
                  String telphone = rowdata.getCell(5).getStringCellValue();//联系人手机号码
                  String mail = rowdata.getCell(6).getStringCellValue();//联系人电子邮件
                  String postalcode = rowdata.getCell(7).getStringCellValue();//邮政编码
                  String addr = rowdata.getCell(8).getStringCellValue();//通信地址
                  String sponsor =rowdata.getCell(9).getStringCellValue();//主管单位
                  String unit = rowdata.getCell(10).getStringCellValue();//推荐单位
                  String type = rowdata.getCell(11).getStringCellValue();//基地类型
                  String department = rowdata.getCell(12).getStringCellValue();//科普部门名称
                  String popular = rowdata.getCell(13).getStringCellValue();//专职科普人数
                  String parttime = rowdata.getCell(14).getStringCellValue();//兼职科普人数
                  String volunteer = rowdata.getCell(15).getStringCellValue();//科普志愿者人数
                  Double funds;
                  if("".equals(rowdata.getCell(16).getStringCellValue())){
                      continue;
                  }else {
                      funds = Double.parseDouble(rowdata.getCell(16).getStringCellValue());//年度科普经费总额
                  }
                  String synopsis = rowdata.getCell(17).getStringCellValue();//单位简介
                  //一整行为空就全部结束
                  if("".equals(name) && "".equals(contacts)  && "".equals(phone) && "".equals(fax) &&
                          "".equals(telphone) && "".equals(mail) && "".equals(addr) && "".equals(postalcode)
                      && "".equals(sponsor) && "".equals(unit) &&"".equals(type) && "".equals(department) && "".equals(popular)
                      && "".equals(parttime) && "".equals(volunteer) && "".equals(funds) && "".equals(synopsis)){
                      break;
                  }

                  if(!StringUtils.hasText(name)){
                      msg += "第"+(i+1)+"行,科普教育基地名称为空";
                      continue;
                  }

                  if("普通类".equals(type)){
                      type="1";
                  }else if("传媒类".equals(type)){
                      type="2";
                  }

                  RisenTradeBase tradeBase = new RisenTradeBase();
                  if(StringUtils.hasText(name)){
                      tradeBase.setRisentbName(name);
                      tradeBase = this.getRisenTradeBaseDao().findByName(tradeBase);
                      if(tradeBase != null){
                          msg += "第"+(i+1)+"行,"+name+"已存在!";
                          continue;
                      }else{
                          risenTradeBase.setRisentbName(name);
                          risenTradeBase.setRisentbContacts(contacts);
                          risenTradeBase.setRisentbPhone(phone);
                          risenTradeBase.setRisentbFax(fax);
                          risenTradeBase.setRisentbTelphone(telphone);
                          risenTradeBase.setRisentbMail(mail);
                          risenTradeBase.setRisentbAddr(addr);
                          risenTradeBase.setRisentbPostalcode(postalcode);
                          risenTradeBase.setRisentbSponsor(sponsor);
                          risenTradeBase.setRisentbUnit(unit);
                          risenTradeBase.setRisentbType(type);
                          risenTradeBase.setRisentbDepartment(department);
                          risenTradeBase.setRisentbPopular(Integer.parseInt(popular));
                          risenTradeBase.setRisentbParttime(Integer.parseInt(parttime));
                          risenTradeBase.setRisentbVolunteer(Integer.parseInt(volunteer));
                          risenTradeBase.setRisentbFunds(funds);
                          risenTradeBase.setRisentbSynopsis(synopsis);

                          if(!"".equals(name) || !"".equals(contacts) || !"".equals(phone) ||
                                  !"".equals(fax) ||!"".equals(telphone)||!"".equals(mail) ||!"".equals(addr)
                                  || !"".equals(postalcode) || !"".equals(sponsor) || !"".equals(unit) || !"".equals(type)
                                  || !"".equals(department) || !"".equals(popular) || !"".equals(parttime)|| !"".equals(volunteer)
                                  || !"".equals(funds) || !"".equals(synopsis)){


                              if("".equals(name) || name ==null){
                                  msg += "第"+(i+1)+"行,科普教育基地名称为空!";
                                  continue;
                              }
                              if(contacts.equals("")||contacts==null){
                                  msg += "第"+(i+1)+"行,联系人为空!";
                                  continue;
                              }
                              if(phone.equals("")||phone==null){
                                  msg += "第"+(i+1)+"行,联系人办公电话为空!";
                                  continue;
                              }
                              if(fax.equals("")||fax==null){
                                  msg += "第"+(i+1)+"行,联系人传真号码为空!";
                                  continue;
                              }
                              String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
                              if(telphone.equals("")||telphone==null){
                                  msg += "第"+(i+1)+"行,联系人手机号码为空!";
                                  continue;
                              }
//                                else if (!Pattern.matches(regex, phone)){
//                                    msg = "第"+(i+1)+"行,联系方式不正确!";
//                                    break;
//                                }
                              if(mail.equals("")||mail==null){
                                  msg += "第"+(i+1)+"行,联系人电子邮件为空!";
                                  continue;
                              }
                              if(addr.equals("")||addr==null){
                                  msg += "第"+(i+1)+"行,通信地址为空!";
                                  continue;
                              }
                              if(postalcode.equals("")||postalcode==null){
                                  msg += "第"+(i+1)+"行,邮政编码为空!";
                                  continue;
                              }
                              if(sponsor.equals("")||sponsor==null){
                                  msg += "第"+(i+1)+"行,主管单位为空!";
                                  continue;
                              }
                              if(unit.equals("")||unit==null){
                                  msg += "第"+(i+1)+"行,推荐单位为空!";
                                  continue;
                              }
                              /*if(parentname.equals("")||parentname==null){
                                  msg += "第"+(i+1)+"行,上级组织为空!";
                                  continue;
                              }*/

                              if(type.equals("")||type==null){
                                  msg += "第"+(i+1)+"行,基地类型为空!";
                                  continue;
                              }
                              if(department.equals("")||department==null){
                                  msg += "第"+(i+1)+"行,科普部门名称为空!";
                                  continue;
                              }
                              if(popular.equals("")||popular==null){
                                  msg += "第"+(i+1)+"行,专职科普人数为空!";
                                  continue;
                              }
                              if(parttime.equals("")||parttime==null){
                                  msg += "第"+(i+1)+"行,兼职科普人数为空!";
                                  continue;
                              }
                              if(volunteer.equals("")||volunteer==null){
                                  msg += "第"+(i+1)+"行,科普志愿者人数为空!";
                                  continue;
                              }
                              if(funds.equals("")||funds==null){
                                  msg += "第"+(i+1)+"行,年度科普经费总额为空!";
                                  continue;
                              }
                              if(synopsis.equals("")||synopsis==null){
                                  msg += "第"+(i+1)+"行,单位简介为空!";
                                  continue;
                              }
                              //获取登录账号的所在科室与uuid
                              CoreAccountLogin cal = (CoreAccountLogin) newModel().operator();
                              risenTradeBase.setRisentbParentUuid(cal.orgOwner().get(0).getCrorgUuid());//科室uuid
                              //2.根据科室的uuid去查询出对应信息
                              RisenTradeBase risenTradeBase1 = irisenTradeBaseDao.findByUuid(risenTradeBase);
                              //3.获取数据
                              risenTradeBase.setRisentbParentName(risenTradeBase1.getRisentbName());//科室
                              k = this.save(risenTradeBase);
                              if(k==1){
                                  msg+="第"+(i+1)+"行:导入成功";
                                  continue;
                              }
                          }else{
                              msg += "第"+(i+1)+"行,导入失败";
                              continue;
                          }
                      }
                  }
              }
          }
//            list.add(risenLearn);
//            if(list.size()>0 && "".equals(msg)){
//                getRisenLearnDao().batchSave(list);
//                msg += "导入成功!";
//            }
      }catch (Exception e){
          msg = "操作失败!";
          e.printStackTrace();
      }
      return msg;
  }

  1. 导入模板
发布了33 篇原创文章 · 获赞 2 · 访问量 4735

猜你喜欢

转载自blog.csdn.net/qq_36778310/article/details/103118135