导入Excle

/**
  * 导入Excle
  * @throws Exception
  */
 public int importExcel(String path,MultipartFile[] upfiles) throws Exception{
  int count = 0; 
  String fileName = "";
  
  if (upfiles != null && upfiles.length > 0) {
   for (MultipartFile f : upfiles) {
    if (f.isEmpty()) {
     continue;
    } else {
     fileName = f.getOriginalFilename();
     FileUtils.copyInputStreamToFile(f.getInputStream(),new File(path + fileName));
    }
   }
  }
   Workbook wb = WorkbookFactory.create(new File(path+fileName));
   
   int bigProblemId = 0 , smallProblemId = 0,allPrice = 0,levelNo = 0,colLength = 10;
   String problemName = "",sheetName = "",bigProblem= "美容报价",smallProblem = "",phoneTypeName="",brandName="";
   
   RmaMobileInfo rmaMobileInfo = null;
   //rmaRepairCostService.executeBySql("delete from rma_repair_part where part_type = 2");
   // 循环工作表Sheet 
   for(int numSheet = 0; numSheet <  wb.getNumberOfSheets(); numSheet++){ 
    try {
     sheetName = wb.getSheetName(numSheet);
     phoneTypeName = sheetName.split("-")[0];
     brandName = sheetName.split("-")[1];
    } catch (Exception e) {
     // TODO: handle exception
    }
    List rmis =getByProperty("typeName", phoneTypeName);
    if(rmis == null || rmis.size() < 1){
     System.out.println("机型:"+phoneTypeName+" 不存在");
     continue;
    }else{
     rmaMobileInfo = rmis.get(0);
    }
    Sheet hssfSheet = wb.getSheetAt( numSheet);
    if(hssfSheet == null){
     continue; 
    }else{
     //获取sheet的name
     sheetName = hssfSheet.getSheetName();
    }
    
    // 循环行Row   hssfSheet.getLastRowNum();
    for(int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++){ 
     Row hssfRow = hssfSheet.getRow(rowNum);
     if(hssfRow == null){ 
      continue; 
     } 
     smallProblem = getValue(hssfRow.getCell((short)0));
     if(smallProblem.equals("综合报价")){
      continue;
     }
     problemName = getValue(hssfRow.getCell((short)1));
     // 循环列Cell   
     for(int cellNum = 3; cellNum <= colLength; cellNum++){ 
      Cell hssfCell = hssfRow.getCell((short)cellNum); 
      if(hssfCell == null || hssfCell.equals("")){ 
       continue; 
      }else{
       String title = getValue((hssfSheet.getRow((short)0)).getCell((short)cellNum));
       Integer costInt = ((Double)(hssfRow.getCell((short)cellNum).getNumericCellValue()*100)).intValue();
       if(costInt == 0 ){
        continue;
       }
       RmaRepairPart part = new RmaRepairPart();
       part.setBrand(sheetName);
       part.setName(smallProblem);
       part.setPartName(title);
       part.setCost(null);
       part.setParentName(bigProblem);
       part.setPartValue(costInt);
       part.setPartType(2);
       part.setPhoneInfo(rmaMobileInfo.getTypeName());
       part.setEccPhoneId(rmaMobileInfo.getEccTypeId());
       part.setRmaPhoneId(rmaMobileInfo.getId());
       rmaRepairPartService.save(part);
       
      }
      
     } 
    } 
   } 
   
   
   
   
   
   
   
   
   
   
   
   
   
   ///this.dao.save(t);
   
   
   
  /* user.setUsername(getCellValue(row.getCell(0)));
   user.setPassword(getCellValue(row.getCell(1)));
   user.getRole().setId(getRoleId(getCellValue(row.getCell(2))));*/
  /* if (getCellValue(row.getCell(3)).equals("全部")) {
    user.getArea().setId(0);
   }else{
    int aid = getAreaId(getCellValue(row.getCell(3)));
    user.getArea().setId(aid);
   }
   if (getCellValue(row.getCell(4)).equals("全部")) {
    user.getSchool().setId(0);
   }else{
    user.getSchool().setId(getSchoolId(getCellValue(row.getCell(4))));
   }
   if (getCellValue(row.getCell(5)).equals("yes")) {
    user.setQuery_prower(1);
   }else{
    user.setQuery_prower(0);
   }
   if (getCellValue(row.getCell(6)).equals("yes")) {
    user.setAdd_prower(1);
   }else{
    user.setAdd_prower(0);
   }
   if (getCellValue(row.getCell(7)).equals("yes")) {
    user.setEdit_prower(1);
   }else{
    user.setEdit_prower(0);
   }
   if (getCellValue(row.getCell(8)).equals("yes")) {
    user.setRemove_prower(1);
   }else{
    user.setRemove_prower(0);
   }
   count += addUser(user);*/
 /* }
  return count;*/
   return 0;
 }
 
 
 
 @SuppressWarnings("static-access") 
 private String getValue(Cell cell){ 
  if (cell == null) {
            return "";
        }
  String strCell = "";
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_STRING:
            strCell = cell.getStringCellValue();
            break;
        case HSSFCell.CELL_TYPE_NUMERIC:
         BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
         strCell = bd.toPlainString();
            strCell = String.valueOf(cell.getNumericCellValue());
            break;
        case HSSFCell.CELL_TYPE_BOOLEAN:
            strCell = String.valueOf(cell.getBooleanCellValue());
            break;
        case HSSFCell.CELL_TYPE_BLANK:
            strCell = "";
            break;
        default:
            strCell = "";
            break;
        }
        if (strCell.equals("") || strCell == null) {
            return "";
        }
       
        return strCell;
 }
 


 //导出

  @RequestMapping(value = "admin/exportDill")
 public void exportDill(ModelAndView mav, HttpServletRequest request,
   HttpServletResponse response) {

  List list = (List) rmaBillDetailService
    .createQueryModelByHql("from RmaBillDetail").query();

  if (list != null && list.size() > 0) {
   // 第一步,创建一个webbook,对应一个Excel文件
   HSSFWorkbook wb = new HSSFWorkbook();
   // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet

   HSSFSheet sheet = wb.createSheet("订单明细单");
   sheet.setDefaultColumnWidth(25);
   sheet.setDefaultRowHeight((short) 500);
   // 第三步,在sheet中添加表头第0行
   HSSFRow row = sheet.createRow((int) 0);
   // 第四步,创建单元格,并设置值表头 设置表头居中
   Font font = wb.createFont();
   font.setFontHeightInPoints((short) 10);// 设置字号
   font.setFontName("黑体");// 设置字体
   // font.setStrikeout(true);//设置是否强调
   CellStyle style = wb.createCellStyle();
   style.setFont(font);
   style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
   HSSFCell cell = row.createCell(0);
   cell.setCellValue("订单编号");
   cell.setCellStyle(style);
   cell = row.createCell(1);
   cell.setCellValue("子单号");
   cell.setCellStyle(style);
   cell = row.createCell(2);
   cell.setCellValue("IMEI码");
   cell.setCellStyle(style);
   cell = row.createCell(3);
   cell.setCellValue(" 保内保外 ");
   cell.setCellStyle(style);
   cell = row.createCell(4);
   cell.setCellValue("时间段");
   cell.setCellStyle(style);
   cell = row.createCell(5);
   cell.setCellValue("地区");
   cell.setCellStyle(style);
   cell = row.createCell(6);
   cell.setCellValue("型号");
   cell.setCellStyle(style);
   cell = row.createCell(7);
   cell.setCellValue("制式");
   cell.setCellStyle(style);
   cell = row.createCell(8);
   cell.setCellValue("故障 ");
   cell.setCellStyle(style);
   cell = row.createCell(9);
   cell.setCellValue("购买时间 ");
   cell.setCellStyle(style);
   cell = row.createCell(10);
   cell.setCellValue("使用时长 ");
   cell.setCellStyle(style);
   cell = row.createCell(11);
   cell.setCellValue("服务类型");
   cell.setCellStyle(style);
  

   for (int i = 0; i < list.size(); i++) {
    row = sheet.createRow((int) i + 1);
    RmaBillDetail bd = list.get(i);
    // 根据子单据号查询 故障
    List rmaDetailCostLogList = (List) rmaDetailCostLogService.createQueryModelByHql("from RmaDetailCostLog where detailNo=?",bd.getDetailNo()).query();
    // RmaDetailCostLog RmaDetailCost= rmaDetailCostLogList.get(i);
    StringBuffer sb = new StringBuffer();
    for (int j = 0; j < rmaDetailCostLogList.size(); j++) {
     String broken=rmaDetailCostLogList.get(j).getCostName();
     String str=null;
     if(broken.indexOf("、")!=-1){
       str=broken.substring(broken.indexOf("、")+1);
       System.out.println(str);     
     }else{
      str=broken;
      
     }
       String appenCont=(j+1) +"、"+ str+" ";
       sb.append(appenCont);
    
     
    }
    String breakdown = sb.toString();
    // 第四步,创建单元格,并设置值
    row.createCell((short) 0).setCellValue(bd.getBill().getBillNo());
    row.createCell((short) 1).setCellValue(bd.getDetailNo());
    row.createCell((short) 2).setCellValue(bd.getImeiEsn());
    row.createCell((short) 6).setCellValue(bd.getPhoneType());
    if (bd.getBill().getBillType() == 2) {

     row.createCell((short) 11).setCellValue("本地网点");
    } else {

     row.createCell((short) 11).setCellValue("原厂维修");
    }
    row.createCell((short) 8).setCellValue(breakdown);
    
    // 根据imei编号,查询imei相关信息
    if(bd.getBill()!=null){
     List imeiInfols = (List) rmaImeiInfoService.createQueryModelByHql("from RmaImeiInfo where imei = ?",bd.getImeiEsn()).query();
     RmaImeiInfo imeiInfo = null;
     if (imeiInfols != null && imeiInfols.size() > 0) {

      imeiInfo = imeiInfols.get(0);
      row.createCell((short) 5).setCellValue(imeiInfo.getAcceptAddress());
      row.createCell((short) 7).setCellValue(imeiInfo.getMobClass());

      SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String dates=null;
      if(bd.getBuyTime()!=null){
       dates = simple.format(bd.getBuyTime());
       row.createCell((short) 9).setCellValue(dates);
         
     
      /*
       * 有延保 只关注 当前时间 < 延保开始时间+延保周期 保内 否则保外没有延保
       * 按15个月(366+92天)+出厂日期 计算是否保内
       */
      String wType = imeiInfo.getwType();// 延保类型
      String period = imeiInfo.getwPeriod();// 延保周期
      String outStoreDate = simple.format(imeiInfo.getOutStoreDate());// 出厂时间
      String flag = null;// 标识
      String date = null;
      Date d = new Date(); // 当前时间
      Date outDate;// 保修最后的期限时间
      if (null == wType || "".equals(wType) || null == period
        || "".equals(period)) {
       // 没有使用延保卡
       outDate = Utils.getBeforeAfterDate(outStoreDate, 458);
       if (d.before(outDate)) {
        flag = "保内";
       } else {
        flag = "保外";
       }

       date = outStoreDate + "~" +simple.format(outDate);
      } else {
       String wStartTime = imeiInfo.getwStartTime().toString();// 保修卡开始时间
       int end = Integer.parseInt(period);// 月份
       DateFormat format2 = new SimpleDateFormat(
         "yyyy-MM-dd HH:mm:ss");
       Date startTime = null;
       try {
        startTime = format2.parse(wStartTime);
       } catch (ParseException e) {
        e.printStackTrace();
       }
       Calendar c = Calendar.getInstance();
       c.setTime(startTime);
       c.add(c.MONTH, end);// 月份的计算
       outDate = c.getTime();
       if (d.before(outDate)) {
        flag = "保内";
       }
       else {
        flag = "保外";
       }
       date = simple.format(startTime) + "~"+ simple.format(outDate);
      }
      try {
       Date dat=simple.parse(dates);
       long diff = d.getTime() - dat.getTime();
       long days = diff /(1000 * 60 * 60 * 24);
          row.createCell((short) 10).setCellValue(days+"天");
      } catch (ParseException e) {
       e.printStackTrace();
      }
      row.createCell((short) 3).setCellValue(flag);
      row.createCell((short) 4).setCellValue(date);

     }
      }  
     
    }
    
   }
   OutputStream outputStream = null;
   try {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    response.reset();
    response.setContentType("application/x-msdownload");
    response.setHeader(
      "Content-Disposition",
      "attachment; filename="
        + java.net.URLEncoder.encode("订单明细单.xls",
          "UTF-8"));
    outputStream = response.getOutputStream();
    wb.write(outputStream);
    outputStream.flush();
    outputStream.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

 }

//导出excle

public String execute() throws Exception {
   
    //Criteria cr = rmaBillService.createCriteria();
    //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    //RmaBill bill = JSONUtil.fromJson(b, RmaBill.class);

    /*if (!StringUtils.isBlank(endTime)) {
     Date end = sdf.parse(endTime + " 23:59:59");
     if (end != null)
      cr.add(Restrictions.le("createTime", end));
    }
    if (!StringUtils.isBlank(startTime)) {
     Date start = sdf.parse(startTime + " 00:00:00");
     if (start != null)
      cr.add(Restrictions.ge("createTime", start));
    }
    if (bill != null) {
     if (!StringUtils.isBlank(bill.getBillNo())) {
      cr.add(Restrictions.like("billNo", "%"
        + bill.getBillNo().toUpperCase() + "%"));
     }
     if (!StringUtils.isBlank(bill.getLinkName())) {
      cr.add(Restrictions.like("linkName", "%" + bill.getLinkName()
        + "%"));
     }
     if (!StringUtils.isBlank(bill.getLinkPhone())) {
      cr.add(Restrictions.like("linkPhone", "%" + bill.getLinkPhone()
        + "%"));
     }
    }
    cr.addOrder(org.hibernate.criterion.Order.desc("id"));
    cr.add(Restrictions.isNull("isTemp"));
    List RmaBillList = (List) rmaBillService.createQueryModelByCriteria(cr).query();
    List list=new ArrayList();
    
     for(RmaBill bills:RmaBillList){   
     List rmaBillDetails= bills.getRmaBillDetails();
     for(RmaBillDetail rmas:rmaBillDetails){
      
      list.add(rmas);
     }
     
     } */
    
  /*
    List list = (List) rmaBillDetailService
      .createQueryModelByHql("from RmaBillDetail").query();*/

    //if (list != null && list.size() > 0) {
     // 第一步,创建一个webbook,对应一个Excel文件
     HSSFWorkbook wb = new HSSFWorkbook();
     // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
     
    

     HSSFSheet sheet = wb.createSheet("订单明细单");
     sheet.setDefaultColumnWidth(25);
     sheet.setDefaultRowHeight((short) 500);
     // 第三步,在sheet中添加表头第0行
     HSSFRow row = sheet.createRow((int) 0);
     // 第四步,创建单元格,并设置值表头 设置表头居中
     Font font = wb.createFont();
     font.setFontHeightInPoints((short) 10);// 设置字号
     font.setFontName("黑体");// 设置字体
     // font.setStrikeout(true);//设置是否强调
     CellStyle style = wb.createCellStyle();
     style.setFont(font);
     style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
     HSSFCell cell = row.createCell(0);
     cell.setCellValue("订单编号");
     cell.setCellStyle(style);
     cell = row.createCell(1);
     cell.setCellValue("子单号");
     cell.setCellStyle(style);
     cell = row.createCell(2);
     cell.setCellValue("IMEI码");
     cell.setCellStyle(style);
     cell = row.createCell(3);
     cell.setCellValue(" 保内保外 ");
     cell.setCellStyle(style);
     cell = row.createCell(4);
     cell.setCellValue("时间段");
     cell.setCellStyle(style);
     cell = row.createCell(5);
     cell.setCellValue("地址");
     cell.setCellStyle(style);
     cell = row.createCell(6);
     cell.setCellValue("型号");
     cell.setCellStyle(style);
     cell = row.createCell(7);
     cell.setCellValue("制式");
     cell.setCellStyle(style);
     cell = row.createCell(8);
     cell.setCellValue("故障 ");
     cell.setCellStyle(style);
     cell = row.createCell(9);
     cell.setCellValue("购买时间 ");
     cell.setCellStyle(style);
     cell = row.createCell(10);
     cell.setCellValue("使用时长 ");
     cell.setCellStyle(style);
     cell = row.createCell(11);
     cell.setCellValue("服务类型");
     cell.setCellStyle(style);
     //HSSFCell.ENCODING_UTF_16;
     
     
     // 第四步,创建单元格,并设置值
     row.createCell((short) 0).setCellValue("z347324932");
     row.createCell((short) 1).setCellValue("z347324932-1");
     row.createCell((short) 2).setCellValue("47848384394");
     row.createCell((short) 6).setCellValue("N5");
     row.createCell((short) 5).setCellValue("长沙");
    

     /*for (int i = 0; i < list.size(); i++) {
      row = sheet.createRow((int) i + 1);
      RmaBillDetail bd = list.get(i);
      // 根据子单据号查询 故障
      List rmaDetailCostLogList = (List) rmaDetailCostLogService.createQueryModelByHql("from RmaDetailCostLog where detailNo=?",bd.getDetailNo()).query();
      // RmaDetailCostLog RmaDetailCost= rmaDetailCostLogList.get(i);
      StringBuffer sb = new StringBuffer();
      for (int j = 0; j < rmaDetailCostLogList.size(); j++) {
       String broken=rmaDetailCostLogList.get(j).getCostName();
       String str=null;
       if(broken.indexOf("、")!=-1){
         str=broken.substring(broken.indexOf("、")+1);
         System.out.println(str);     
       }else{
        str=broken;
        
       }
         String appenCont=(j+1) +"、"+ str+" ";
         sb.append(appenCont);
      
       
      }
      String breakdown = sb.toString();
      // 第四步,创建单元格,并设置值
      row.createCell((short) 0).setCellValue(bd.getBill().getBillNo());
      row.createCell((short) 1).setCellValue(bd.getDetailNo());
      row.createCell((short) 2).setCellValue(bd.getImeiEsn());
      row.createCell((short) 6).setCellValue(bd.getPhoneType());
      row.createCell((short) 5).setCellValue(bd.getBill().getLinkAddress());
      if (bd.getBill().getBillType() == 2) {

       row.createCell((short) 11).setCellValue("本地网点");
      } else {

       row.createCell((short) 11).setCellValue("原厂维修");
      }
      row.createCell((short) 8).setCellValue(breakdown);
      
      // 根据imei编号,查询imei相关信息
      if(bd.getBill()!=null){
       List imeiInfols = (List) rmaImeiInfoService.createQueryModelByHql("from RmaImeiInfo where imei = ?",bd.getImeiEsn()).query();
       RmaImeiInfo imeiInfo = null;
       if (imeiInfols != null && imeiInfols.size() > 0) {

        imeiInfo = imeiInfols.get(0);
        
        row.createCell((short) 7).setCellValue(imeiInfo.getMobClass());

        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dates=null;
        if(bd.getBuyTime()!=null){
         dates = simple.format(bd.getBuyTime());
         row.createCell((short) 9).setCellValue(dates);
           
       
        
         * 有延保 只关注 当前时间 < 延保开始时间+延保周期 保内 否则保外没有延保
         * 按15个月(366+92天)+出厂日期 计算是否保内
        
        String wType = imeiInfo.getwType();// 延保类型
        String period = imeiInfo.getwPeriod();// 延保周期
        String outStoreDate = simple.format(imeiInfo.getOutStoreDate());// 出厂时间
        String flag = null;// 标识
        String date = null;
        Date d = new Date(); // 当前时间
        Date outDate;// 保修最后的期限时间
        if (null == wType || "".equals(wType) || null == period
          || "".equals(period)) {
         // 没有使用延保卡
         outDate = Utils.getBeforeAfterDate(outStoreDate, 458);
         if (d.before(outDate)) {
          flag = "保内";
         } else {
          flag = "保外";
         }

         date = outStoreDate + "~" +simple.format(outDate);
        } else {
         String wStartTime = imeiInfo.getwStartTime().toString();// 保修卡开始时间
         int end = Integer.parseInt(period);// 月份
         DateFormat format2 = new SimpleDateFormat(
           "yyyy-MM-dd HH:mm:ss");
         Date startTimes = null;
         try {
          startTimes = format2.parse(wStartTime);
         } catch (ParseException e) {
          e.printStackTrace();
         }
         Calendar c = Calendar.getInstance();
         c.setTime(startTimes);
         c.add(c.MONTH, end);// 月份的计算
         outDate = c.getTime();
         if (d.before(outDate)) {
          flag = "保内";
         }
         else {
          flag = "保外";
         }
         date = simple.format(startTime) + "~"+ simple.format(outDate);
        }
        try {
         Date dat=simple.parse(dates);
         long diff = d.getTime() - dat.getTime();
         long days = diff /(1000 * 60 * 60 * 24);
            row.createCell((short) 10).setCellValue(days+"天");
        } catch (ParseException e) {
         e.printStackTrace();
        }
        row.createCell((short) 3).setCellValue(flag);
        row.createCell((short) 4).setCellValue(date);

       }
        }  
       
      }
      
     }*/
     OutputStream outputStream = null;
     try {
      HttpServletResponse response=  ServletActionContext.getResponse();
      response.setContentType("text/html;charset=utf-8");
      response.setCharacterEncoding("UTF-8");
      response.reset();
      response.setContentType("application/msexcel");
      response.setHeader("Content-Disposition","attachment; filename="+ java.net.URLEncoder.encode("订单明细单.xls","UTF-8"));
      outputStream = response.getOutputStream();
     /* ConnectionFactory conn = (ConnectionFactory) new SingleConnectionFactory();
      JmsTemplate jms=new JmsTemplate(conn);*/
       
     
      wb.write(outputStream);
      outputStream.close();
     } catch (Exception e) {
      e.printStackTrace();
     }
    //}

   //}
 
   
    
    
 
  return null;
 }

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(导入Excle)