平时我们在开发后端管理的系统时,经常会出现导出Excel的功能。这个功能很简单,但是呢,我一般就会使用公用的工具类,在一个Util中,暴露公用导出的接口,只需要传入需要导出的数据(一般使用list集合)以及需要导出的key-value字段和值的模板(这里使用了org.json,更加轻量话)。

一、废话不多说,直接先上暴露给用户的controller层的代码.这里呢,更改了header,通知浏览器打开下载功能(Content-Disposition 和attachment;filename一起使用)。然后只需要从数据库中调用需要导出的数据,这里我就直接调用所有的数据。

/**
     * 导出excel
     * @param response
     */
    @RequestMapping(value = "exportExcel",method = RequestMethod.GET)
    public void  exportExcel(HttpServletResponse response){

        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.reset();
            String header = "attachment; filename="
                    + URLEncoder.encode("业主信息.xls", "UTF-8");
            response.setHeader("Content-Disposition", header);
            response.setContentType("application/octet-stream; charset=utf-8");
            List<Owner> owners = ownerService.findAll();
            ownerService.exportExcel(owners,out);

            out.flush();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out!=null){
                    out.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }

二、Service的代码,对应  ownerService.exportExcel(owners,out);    传入了需要导出的集合,以及需要导出的out流。

 @Override
     public void exportExcel(List<Owner> owners, OutputStream out){
         JSONArray jsonArray = new JSONArray();
         List<Map<String, String>> eventRecordMapList = new ArrayList<Map<String, String>>();

         JSONObject jsonObject = new JSONObject();
         jsonObject.accumulate("headerName", "序号");
         jsonObject.accumulate("header", "id");
         jsonArray.put(jsonObject);
         jsonObject = new JSONObject();
         jsonObject.accumulate("headerName", "业主姓名");
         jsonObject.accumulate("header", "name");
         jsonArray.put(jsonObject);
         jsonObject = new JSONObject();
         jsonObject.accumulate("headerName", "业主开户银行");
         jsonObject.accumulate("header", "bankName");
         jsonArray.put(jsonObject);
         jsonObject = new JSONObject();
         jsonObject.accumulate("headerName", "业主开户银行账号");
         jsonObject.accumulate("header", "bankAccount");
         jsonArray.put(jsonObject);
         jsonObject = new JSONObject();
         jsonObject.accumulate("headerName", "供应商");
         jsonObject.accumulate("header", "vendor");
         jsonArray.put(jsonObject);
         jsonObject = new JSONObject();
         jsonObject.accumulate("headerName", "代付金额");
         jsonObject.accumulate("header", "payed");
         jsonArray.put(jsonObject);

         for (int i = 0; i < owners.size(); i++) {

             Owner owner = owners.get(i);
             Map<String, String> recordMap = new HashMap<String, String>();
             recordMap.put("id",owner.getId().toString());
             recordMap.put("name", owner.getName());
             recordMap.put("bankName", owner.getBankName());
             recordMap.put("bankAccount",owner.getBankAccount());
             recordMap.put("vendor",owner.getVendor());
             if (owner.getPayed()!=null){
                 recordMap.put("payed",owner.getPayed().toString());
             }else {
                 recordMap.put("payed","0");
             }

             eventRecordMapList.add(recordMap);
         }

         ExcelUtils exportExcel = new ExcelUtils();
         exportExcel.exportExcel("业主信息", jsonArray, eventRecordMapList, out);
     }

这一块呢,使用了org.json  ,如果亲们要使用我的代码,就要在项目中引入org.json  ,maven引用如下

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20151123</version>
        </dependency>

Service中的代码,主要是为了通过key-value的形式将数据全部进行整理,以便用通用的接口实现导出

三 、本块代码就是核心的Util中的通用工具类,这个通用工具类可以通过定制,继承的方式无限扩展适用的业务逻辑,比如可以扩展那些字段导出是需要下拉的,哪些是不能修改的等等,都可以扩展,这个考验扩展人的接口封装功底(我就特别喜欢封装公用接口给别人用,那种成就感很爽,不过就要考虑很多业务逻辑的情况),请打开查看哦,写得不是很复杂,不过也要慢慢看看就会懂了,就是一个公用方法。这样的好处就是,不管以后哪些板块用到导出功能,就不用再去写excel的操作代码了,只需要在模块的service中定义需要导出的字段,告诉Excel的栏目这些等等。还是那句话,util中的导出逻辑还可以继承修改,也更好的实现了扩展性。

 public void exportExcel(String title, JSONArray jsonArray, List<Map<String, String>> eventRecordMapList,
                             OutputStream out) {
         // 创建一个excel工作簿
         HSSFWorkbook workbook = new HSSFWorkbook();
         HSSFSheet sheet = workbook.createSheet(title);
         // excel列默认宽度
         sheet.setDefaultColumnWidth(20);

         // 第一行标题样式(白字蓝底)
         HSSFCellStyle titleStyle = workbook.createCellStyle();
         HSSFPalette palette = workbook.getCustomPalette();
         palette.setColorAtIndex((short) 63, (byte) (50), (byte) (126), (byte) (179));
         titleStyle.setFillForegroundColor((short) 63);
         titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
         titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
         titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
         titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
         titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
         titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
         HSSFFont font = workbook.createFont();
         font.setColor(HSSFColor.WHITE.index);
         font.setFontHeightInPoints((short) 12);
         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
         titleStyle.setFont(font);
         titleStyle.setWrapText(false);

         // 内容行样式 (白底黑字)
         HSSFCellStyle contentStyle = workbook.createCellStyle();
         contentStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
         contentStyle.setFillForegroundColor(HSSFColor.WHITE.index);
         contentStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
         contentStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
         contentStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
         contentStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
         contentStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
         contentStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
         HSSFFont font2 = workbook.createFont();
         font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
         contentStyle.setFont(font2);
         contentStyle.setWrapText(true);

         HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
         HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
         comment.setString(new HSSFRichTextString("数据列表"));
         comment.setAuthor("csh");

         // 填充标题,就是第一行啦
         HSSFRow row = sheet.createRow(0);
         row.setHeight((short) 500);
         for (short i = 0; i < jsonArray.length(); i++) {
             HSSFCell cell = row.createCell(i);
             cell.setCellStyle(titleStyle);
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             HSSFRichTextString text = new HSSFRichTextString(jsonObject.getString("headerName"));
             cell.setCellValue(text);
         }

         // 填充内容行,就是除第一行外的所有行,从第二行开始
         for (int i = 0; i < eventRecordMapList.size(); i++) {
             row = sheet.createRow(i + 1);
             row.setHeight((short) 350);
             Map<String, String> eventRecordMap = eventRecordMapList.get(i);

             for (int j = 0; j < jsonArray.length(); j++) {
                 JSONObject jsonObject = jsonArray.getJSONObject(j);
                 HSSFCell cell = row.createCell(j);
                 cell.setCellStyle(contentStyle);
                 try {
                     String textValue = eventRecordMap.get(jsonObject.getString("header"));

                     if (textValue != null) {
                         Pattern p = Pattern.compile("^//d+(//.//d+)?$"); // 匹配是否是数值类型
                         Matcher matcher = p.matcher(textValue);
                         if (matcher.matches()) {
                             cell.setCellValue(Double.parseDouble(textValue));
                         } else {
                             HSSFRichTextString richString = new HSSFRichTextString(textValue);
                             HSSFFont font3 = workbook.createFont();
                             font3.setColor(HSSFColor.BLACK.index);
                             richString.applyFont(font3);
                             cell.setCellValue(richString);
                         }
                     }

                 } catch (Exception e) {
                     e.printStackTrace();
                 } finally {

                 }
             }

         }
         try {
             workbook.write(out);// 将excel工作簿写入到输出流中
             // workbook.close();//关闭

         } catch (IOException e) {
             e.printStackTrace();
         }

     }
04-18 02:20
查看更多