JAVA导入EXCEL文件,并且返回详细的导入信息(包括:成功、失败、原因)绝版

需要引入的文件全部由我自己封装(包括:Base64Util.java),随后几篇文章里我会逐个提供:







form表单

<%-- --%>

返回导入信息展示所需的div

数据导入情况分析: 关闭
总条数 成功数 失败数

相关的JS方法:

function alter(){
  var v = $("#uploadEventFile").val();
  if(v != ""){
    // 避免多次点击按钮导致重复提交表单,msg反回页面后,页面会自动刷新,disabled将被解除	lenian 2018 06 14
      $('#submitBtn').attr('disabled',true);
      return true;
  } else {
    //confirm('请选择excel,再导入!');
    alert("请选择您需要导入的Excel!");
      return false;
  }
}

表单提交:

// submit提交方法(传参数),原因:有些站段同时属于多个处室,必须通过传值判断
function toSubmit() {
  var officeid = getUrlParam("officeid");
    if(officeid == null) {
      officeid = $("#deptid").val();
    } else {
    officeid = getUrlParam("officeid").replace("#", "")
    }
    $("#deptid", "#batchUpload").val(officeid);
}

注:该方法用作页面接收参数用,适用于JSP、html等

function getUrlParam(k) {
    var regExp = new RegExp('([?]|&)' + k + '=([^&]*)(&|$)');
    var result = window.location.href.match(regExp);
    if (result) {
        return decodeURIComponent(result[2]);
    } else {
        return null;
    }
}
后台方法:
/**
 * @author lenian
 * @Description: 机务、运输、货运等工作量数据导入(导入Excel)
 * @date lenian 2018 07 03
 * @return
 * @throws Exception 
 */
@Action(value = "impPortfolioExcel", results = { @Result(name = "impPortfolioExcel", location = "${ctx}/security/base/peoplesafeimg!impPortfolioExcel.action?resultMsg=${resultMsg}&deptid=${deptid}", type = "redirect") })
public String impPortfolioExcel() throws Exception
{
  List> result = new ArrayList<>();
  if (upload != null) {  
    Attachment fileUpload = attachManager.fileUpload(upload,uploadFileName);
    String path = fileUpload.getSavePath() + fileUpload.getSaveFileName();
    //判断:前台导入数据之前选择需要导入的数据类型  lenian 2018 03 13
    String tab = "portfolio";//自定义:导入工作量数据的标识(表名),只做判断用,不存库  lenian 修改于 2018 06 08
    if (PathUtil.getPath(path) !=0 || PathUtil.getPath(path) == 1) {
      result = peopleSafeImgManager.tabImpExcel(fileUpload.getSavePath() + fileUpload.getSaveFileName(), tab, deptid);
    } else if (PathUtil.getPath(path) !=0 || PathUtil.getPath(path) == 2) {
      result = peopleSafeImgManager.tabImpExcel(fileUpload.getSavePath() + fileUpload.getSaveFileName(), tab, deptid);    
    }
  }
  try {
    String jsonArray = JSON.toJSONString(result);
    resultMsg = Base64Util.encodeData(jsonArray);  // 加密操作
  } catch (Exception e) {
    e.printStackTrace();
  }
  return "impPortfolioExcel";
}
private final static String XLS = "xls";
private final static String XLSX = "xlsx";
/**
 * @author lenian
 * @Description:工作量、诚信导入(趋向单表导入)+ 技术业务考核、两纪及作业标准、个人荣誉导入
 * @date lenian 2018 06 07
 * @return
 * @throws Exception String
 */
@SuppressWarnings({ "unused", "deprecation" })
public List> tabImpExcel(String path, String tab, Long deptid) {
		
  // 返回导入提示信息、统计信息(总数、成功数、失败数)
  List> list = new ArrayList<>();
  List> messages = new ArrayList>();
  Map map = new HashMap<>(); // 存放统计的数量(总数、成功、失败)
  int sum = 0; ///总条数
  int success = 0;  ///成功数(总数-失败数)
  int fail = 0;  ///失败
    
  BufferedInputStream bis;
  Workbook wb = null ;
    
  File file = new File(path);
  FileInputStream fis = null;
  try {
    fis = new FileInputStream(file);
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }
    
  try {
    if(path.endsWith(XLS)){  // 2003
      wb = new HSSFWorkbook(fis);
    }else if(path.endsWith(XLSX)){ //2007
      wb = new XSSFWorkbook(fis);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
    
  // 总共有多少张sheet表
  int sheetnum = wb.getNumberOfSheets();
    
  for (int i = 0; i < sheetnum; i++) {
    Sheet sheet = wb.getSheetAt(i);
    // 表头数据
    Row namerow = sheet.getRow(0);
      
    // 表头数据
    Row headrow = sheet.getRow(1);
      
    if(null != headrow) {
        
      // 总行数
//        int rowNum = sheet.getPhysicalNumberOfRows();
      int rowNum = sheet.getLastRowNum();
      sum = rowNum;
      // 总列数
      int colNum = headrow.getPhysicalNumberOfCells();
        
      if(rowNum == 0){  //判断工作表是否为空
        continue;
      }
        
      AESOperator aesOperator = AESOperator.getInstance();
        
      Long depotid = SessionManager.getDepartmentId();
      Department department = departmentManager.getObjectById(depotid);
      String depotName = department.getName();// 站段
//        Department parentment = SessionManager.getLoginUserDept().getParent();
      Department parentment = department.getParent();
      String officeName = parentment.getName();// 处室
      Long office_id;
      if (parentment == null) {
        office_id = null;
      } else {
        office_id = parentment.getId();//处室
      }
      //循环行
      for (int j = 1; j <= rowNum; j++) {    
        Row row = sheet.getRow(j);
        if (null == row) {
          continue;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
          
        String dayTime = sdf.format(new Date());  //当前时间
          
        if("portfolio".equals(tab)) {  // 机务、运输、货运等工作量导入,判断:导入的数据类型
          PortraitPortfolio portraitPortfolio = null;
          String str = null;
          if(null != row) {
            String idCard = StringUtils.trim(ReadExcelXlsxUtil.getStringCellvalue(row.getCell(2)));//身份证非空判断
            if (StringUtils.isNotEmpty(idCard) && !StringUtils.equals("null", idCard)) {
              // 当身份证不为空时,将身份证转换为大写  修改于2018 06 22  lenian
              idCard = idCard.toUpperCase();
              // 对身份证号进行校验  lenian 2018 07 04
              boolean existed = AFT.utils.StringUtils.checkIdCard(idCard);
              if (existed == false) {
                String message = "您好,第[ "+ j +" ]行,第[ 3 ]列身份证有误,请重新录入! ";  // 身份证规则判断
                Map mapCard = new HashMap();
                mapCard.put("message", message);
                messages.add(mapCard);
                fail++;  // 失败一条
              } else {
                //根据身份证号查询人员信息,并且查询出人员的工种
                EmployeeInfo emp = this.getEmpByIdcard(idCard);
                if (emp != null) {
                  Date time = null ;
                  if ("".equals(row.getCell(3).toString()) || row.getCell(3).toString() == null) {
                    try {
                      time = ymd.parse(dayTime); // 当前时间
                    } catch (ParseException e) {
                      e.printStackTrace();
                    }
                  } else {
                    try {
                      String st = row.getCell(3).toString();
                      Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
                      Matcher aMatcher = pattern.matcher(st);
                      if (aMatcher.find() == true) {
                        time = ymd.parse(row.getCell(3).getDateCellValue().toLocaleString());
                      } else {
                        time = ymd.parse(row.getCell(3).toString());
                      }
                    } catch (Exception e) {
                      String message = "您好,第[ "+ j +" ]行,第[ 4 ]列日期格式不正确,请重新录入!";  // 判断日期格式是否正确
                      Map mapDate = new HashMap();
                      mapDate.put("message", message);
                      messages.add(mapDate);
                      fail++;  // 失败一条
                      e.printStackTrace();
                    }
                  }
                  portraitPortfolio = portraitPortfolioManager.getByIdCardTime(idCard, time);
                  portraitPortfolio.setTime(time);
                  portraitPortfolio.setIdCard(idCard);
                  // 不同处室导入时存储的字段不同  lenian 2018 06 08
                  if (deptid == 103 || deptid == 1056) {  // 货运处、机务处
                    String sc = StringUtils.trim(ReadExcelXlsxUtil.getStringCellvalue(row.getCell(4)));
                    if (StringUtils.isNotEmpty(sc) && !StringUtils.equals("null", sc)) {
//                      Float score = Float.parseFloat(ReadExcelXlsxUtil.getStringCellvalue(row.getCell(4)));
                      Float score = null;
                      try {
                        score = Float.parseFloat(sc);
                      } catch (Exception e) {
                        String message = "您好,第[ "+ j +" ]行,第[ 5 ]列工作量填写不正确,请重新录入!";  // 判断工作量填写否正确
                        Map mapScore = new HashMap();
                        mapScore.put("message", message);
                        messages.add(mapScore);
                        fail++;  // 失败一条
                        e.printStackTrace();
                      }
                      portraitPortfolio.setScore(score);
                    } else {
                      portraitPortfolio.setScore((float) 0);
                    }
                  } else if (deptid == 102) {  // 运输处
                    float minute = 0;  // 分钟数
                    String mi = StringUtils.trim(ReadExcelXlsxUtil.getStringCellvalue(row.getCell(4)));
                    if (StringUtils.isNotEmpty(mi) && !StringUtils.equals("null", mi)) {
                      minute = Float.parseFloat(mi);
                    }
                    portraitPortfolio.setMinute(minute);
                    float column = 0;  // 列数
                    String co = StringUtils.trim(ReadExcelXlsxUtil.getStringCellvalue(row.getCell(5)));
                    if (StringUtils.isNotEmpty(co) && !StringUtils.equals("null", co)) {
                      column = Float.parseFloat(co);
                    }
                    portraitPortfolio.setColumnNumber(column);
                    float channel = 0;  // 钩数
                    String ch = StringUtils.trim(ReadExcelXlsxUtil.getStringCellvalue(row.getCell(6)));
                    if (StringUtils.isNotEmpty(ch) && !StringUtils.equals("null", ch)) {
                      channel = Float.parseFloat(ch);
                    }
                    portraitPortfolio.setChannelNumber(channel);
                  }
                  portraitPortfolio.setDepot(depotName);
                  portraitPortfolio.setCreateTime(new Date());
                  str = "emp";
                }
                if (str == null) {
                  String message = "您好,第[ "+ j +" ]行人员信息不存在,请确认!";  // 判断是否存在人员信息
                  Map mapEmp = new HashMap();
                  mapEmp.put("message", message);
                  messages.add(mapEmp);
                  fail++;  // 失败一条
                } else {
                  boolean isNotNull = portraitPortfolio.getTime() != null && portraitPortfolio.getScore() != null;
                  if (isNotNull) {
                    if ("机务处".equals(officeName) || "货运处".equals(officeName) ) {
                      portraitPortfolioManager.savePortfolio_01(portraitPortfolio);
                    } else if ("运输处".equals(officeName)) {
                      portraitPortfolioManager.savePortfolio_02(portraitPortfolio);
                    }
                  }
                }
              }
            } else {
              String message = "您好,第[ "+ j +" ]行,第[ 3 ]列身份证号不能为空,请确认!";  // 判断身份证号是否为空
              Map mapNull = new HashMap();
              mapNull.put("message", message);
              messages.add(mapNull);
              fail++;  // 失败一条
            }
          }
        }
      }
    }    
  }
    
//    System.out.println(sum+"\t"+(sum-fail)+"\t"+fail);
  if (fail > sum) {  // 因为不是层级判断,多个字段不符合要求时,避免失败数无限增大
    fail = sum;
  }
    
  map.put("sum", String.valueOf(sum));
  map.put("success", String.valueOf(sum-fail));
  map.put("fail", String.valueOf(fail));
  map.put("messages", messages);
  list.add(map);
  return list;
}

效果图展示,如下:

JAVA导入EXCEL文件,并且返回详细的导入信息(包括:成功、失败、原因)绝版_第1张图片



你可能感兴趣的:(java,excel,poi,js,Base64)