java 导出excel copy 模版

  • 之前也写过 导出excel 各种各样的.但是说实话程序员的记忆真的会下降.以前写的老就忘记了.
  • 这里复制下代码已做mark
  • 下面的代码备注及实现的功能
    • 本来导出是通过反射实体类的字段顺序对应的导入到excel中 但是有的字段需要合并比如(省-市-区-地址)需要合并成一个地址来进行导出
    • 有些字段原来是类型可能只是代码 需要转化成具体的值才可以导出到excel 需要通过反射修改值.
    • excel 有许多公式和样式用java写太麻烦了.直接copy 模版 然后进行导出
    • 导出时选择下载路径导出
    • 对不需要导出的字段进行处理
    • 根据查出来数据分组导入到不同的sheet 中

-大致的代码逻辑就是这样使得本来很整洁的代码让我写的非常臃肿好下面是代码

    public void findCustomerContract(HttpServletResponse response,
            HttpServletRequest request, String pattern,
            Contract contract) {
        String newFileName=null;
        //导出时有界面可以下载
        OutputStream out = null;
        String fileName =String.valueOf(Math.random()*1000);
           if(newFileName!=null && !"".equals(newFileName)){
                fileName = newFileName;
            }
        String fileName1 = fileName.replace(".", "") + ".xls";
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName1, "UTF-8"));
            response.setContentType("application/msexcel");
            // response.setContentType("application/vnd.ms-excel");
        } catch (Exception e1) {
        }
         try {
             //获取模版路劲
             String path = this.getClass().getResource("/").getPath();
//           path = path.substring(1, path.indexOf("WEB-INF/classes/"));
             String filePath = path + "WEB-INF/classes/ftl/contractDataTemplate.xls";
             String filePath1 = path+"ftl/contractDataTemplate.xls";
        File file = new File(filePath1);
        FileInputStream in = new FileInputStream(file);
        HSSFWorkbook wb = new HSSFWorkbook(in);
        HSSFCellStyle style = wb.createCellStyle();
        // 生成一个字体
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 12);
        // 把字体应用到当前的样式
        style.setFont(font);

        List<Office> officeByGrade = officeDao.getOfficeByGrade(contract);
        Map<String,Object> map = new HashMap<String,Object>();
        List<T> findCustomerExcel = null;
        int existCount = 0;
        int pageInt = 0;
        for (Office it : officeByGrade) {
            contract.setSalesDepartment(it.getId());
            findCustomerExcel= (List<T>) statisticsDao.findCustomerExcel(contract);
             if(findCustomerExcel.size() > 0) {
                 pageInt++;
                 existCount++;
                 System.err.println("pageint=" + pageInt);
//              wb.setSheetName(pageInt, it.getName());
                 //有的话就克隆一个
                 wb.cloneSheet(0);
                 wb.setSheetName(pageInt, it.getName());
                 //获取sheet
                HSSFSheet sheetAt = wb.getSheetAt(pageInt);
                 Iterator<T> ite = (Iterator<T>) findCustomerExcel.iterator();
                 //-----------------------处理实体类中需要转换的地方-----------------------------------
                 findCustomerExcel.forEach(next->{
                 Field[] declaredFields = next.getClass().getDeclaredFields();
                 for(int i = 0; i < declaredFields.length; i++ ) {
                     Field field = declaredFields[i];
                     String fieldName = field.getName();
                     try {
                            if(fieldName.equals("cardAddrProvince") ||
                                    fieldName.equals("cardAddrCity")||
                                    fieldName.equals("cardAddrCounty")||
                                    fieldName.equals("addrProvince")||
                                    fieldName.equals("addrCity")||
                                    fieldName.equals("addrCounty")


                                    ) {
                                this.getValue(fieldName, next, field);
                            }else if(fieldName.equals("type")) {
                                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                                Class tCls = next.getClass();
                                Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                                Object value    = getMethod.invoke(next, new Object[] {});
                                String dictLabel = DictUtils.getDictLabel(value.toString(), "type", null);
                                field.setAccessible(true);
                                        field.set(next, dictLabel);
                            }else if(fieldName.equals("bankServerName")) {

                                        String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                                        Class tCls = next.getClass();
                                        Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                                        Object value    = getMethod.invoke(next, new Object[] {});
                                        String dictLabel = DictUtils.getDictLabel(value.toString(), "bank_kind", null);
                                        field.setAccessible(true);
                                        field.set(next, dictLabel);
                            }else if(fieldName.equals("salesDepartment")) {
                                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                                Class tCls = next.getClass();
                                Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                                Object value    = getMethod.invoke(next, new Object[] {});
                                String dictLabel = OfficeUtils.getOffice(value.toString()).getName();
                                field.setAccessible(true);
                                field.set(next, dictLabel);
                            }

                        } catch (Exception e) {
                            log.error("代码转换类型错误",e);

                        }
                 }
                 });
                 //--------------------------处理结束-------------------------------------------------
                 //导出到excel 中
                int index= 1 ;
                HSSFRow row =null;
                while(ite.hasNext()) {
                    index++;
                    //创建行
                    row = sheetAt.createRow(index);
                     T t = (T)ite.next();
                     Field[] fields = t.getClass().getDeclaredFields();
                        try {
                            for (short i = 0; i < fields.length-6; i++) {
                                HSSFCell cell = row.createCell(i);
                                cell.setCellStyle(style);
                                Field field = fields[i];
                                String fieldName = field.getName();
                                Object value =null;
                                //本来可以通过字段发射导出.但是 有些字段需要组合成一起.或者导出的表有固定的值.所以在这里处理下.
                                if(!fieldName.equals("cardAddrProvince") &&
                                    !fieldName.equals("cardAddrCity") &&
                                    !fieldName.equals("cardAddrCounty") &&
                                    !fieldName.equals("cardAddr") &&
                                    !fieldName.equals("addrProvince")&&
                                    !fieldName.equals("addrCity")&&
                                    !fieldName.equals("addrCounty")&&
                                    !fieldName.equals("addr")
                                        ) {
                                if(fieldName.equals("index")) {//序号
                                    value = index-1;
                                }else if(fieldName.equals("mobile1")){//解密手机号
                                    String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                                    Class tCls = t.getClass();
                                    Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                                    value   = getMethod.invoke(t, new Object[] {});
                                    value = AESUtils.decryptHex(value.toString(), Constant.AES_KEY);
                                }else {

                                    String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                                    Class tCls = t.getClass();
                                    Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
                                    value   = getMethod.invoke(t, new Object[] {});
                                }
                                }
                                    // 判断值的类型后进行强制类型转换
                                    String textValue = null;
                                    if (value instanceof Integer) {
                                        int intValue = (Integer) value;
                                        cell.setCellValue(intValue);
                                    } else if (value instanceof Long) {
                                        long longValue = (Long) value;
                                        cell.setCellValue(longValue);
                                    } else if (value instanceof Boolean) {
                                        boolean bValue = (Boolean) value;
                                        textValue = "";
                                        if (!bValue) {
                                            textValue = "0";
                                        }
                                    } else if (value instanceof Date) {
                                        Date date = (Date) value;
                                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                                        textValue = sdf.format(date);
                                    } else {
                                        // 其它数据类型都当作字符串简单处理
                                        if (value == null) {
                                            textValue = "";
                                        } else {
                                            textValue = value.toString();
                                        }

                                    }

                                    if (textValue != null) {
                                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                                        Matcher matcher = p.matcher(textValue);
                                        if (matcher.matches()) {
                                            // 是数字当作double处理
                                            cell.setCellValue(Double.parseDouble(textValue));
                                        } else {
                                            HSSFRichTextString richString = new HSSFRichTextString(textValue);
                                            richString.applyFont(font);
                                            cell.setCellValue(richString);
                                        }
                                    }

                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        } catch (NoSuchMethodException e) {
                            e.printStackTrace();
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        }
                }
            };
        }
        //如果没有数据的话就不删除 有数据在删除
        if(existCount > 0) {
            //因为加载时候有1个所以要删除掉
            wb.removeSheetAt(0);

        }

//      OutputStream stream = new FileOutputStream("d:/22.xls");
//      wb.write(stream);
        out = response.getOutputStream();
        out.flush();
        wb.write(out);
         }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        }

    public  void getValue(String fieldName, T next, Field field) throws Exception{
        String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        Class tCls = next.getClass();
        Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
        Object value    = getMethod.invoke(next, new Object[] {});
        Area area = null;
        if(value !=null ) {
            if(AreaUtils.getArea(value.toString()) !=null) {
                area =  AreaUtils.getArea(value.toString());
                String name = area.getName();
                field.setAccessible(true);
                field.set(next, name);
            }

        }
    }

有不需要以上的功能的同学.可以从代码中抽取需要的功能.来做导出


欢迎加 QQ群:373899683 一起讨论技术(一群菜鸟)

猜你喜欢

转载自blog.csdn.net/qq_29371103/article/details/78557931