zoukankan      html  css  js  c++  java
  • springMVC导出 CSV案例

    导出csv

    第一步 Controller类里调用

    OrderParamsVo 传入的参数
    orderService.findBuyCSV 查询到要导出的信息
     1      /**
     2      * 购买订单CSV
     3      * OrderParamsVo 传入的参数
     4      */
     5     @RequestMapping("findBuyCSV")
     6     @ResponseBody
     7     public JsonResult findBuyCSV(OrderParamsVo params, HttpServletResponse response) {
     8         List<Map<String, Object>> dataList=null;
     9         Validator.getInstance().validate(params);
    10         List<OrderBo> orderBos = orderService.findBuyCSV(params);// 查询到要导出的信息
    11         if (orderBos.size() == 0) {
    12             JsonResult.buildFailedResult("无数据导出");
    13         }
    14         String sTitle = "投资日期,订单号,姓名,购买产品,金额,状态";
    15         String fName = "buywater_";
    16         String mapKey = "createDate,no,realname,productName,money,state";
    17         dataList = new ArrayList<>();
    18         Map<String, Object> map = null;
    19         for (OrderBo order : orderBos) {
    20             map = new HashMap<String, Object>();
    21             map.put("createDate", DateFormatUtils.format(order.getCreateDate(), "yyyy/MM/dd HH:mm"));
    22             map.put("no", order.getNo());
    23             map.put("realname", order.getUserName());
    24             map.put("productName", order.getProductName());
    25             map.put("money", order.getMoney());
    26             map.put("state", order.getState());
    27 
    28             dataList.add(map);
    29         }
    30         try (final OutputStream os = response.getOutputStream()) {
    31             ExportUtil.responseSetProperties(fName, response);
    32             ExportUtil.doExport(dataList, sTitle, mapKey, os);
    33             return null;
    34 
    35         } catch (Exception e) {
    36             logger.error("购买CSV失败", e);
    37 
    38         }
    39         return JsonResult.buildFailedResult("数据导出出错");
    40     }            

    第二步:ExportUtil 类 (公用方法) 关键

     1 package com.util;
     2 
     3 import java.io.OutputStream;
     4 import java.io.UnsupportedEncodingException;
     5 import java.net.URLEncoder;
     6 import java.text.SimpleDateFormat;
     7 import java.util.Date;
     8 import java.util.List;
     9 import java.util.Map;
    10 
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 import org.apache.commons.lang3.time.DateFormatUtils;
    14 import org.slf4j.Logger;
    15 import org.slf4j.LoggerFactory;
    16 
    17 public class ExportUtil {
    18     private static final Logger logger = LoggerFactory.getLogger(ExportUtil.class);
    19     /** CSV文件列分隔符 */
    20     private static final String CSV_COLUMN_SEPARATOR = ",";
    21 
    22     /** CSV文件列分隔符 */
    23     private static final String CSV_RN = "
    ";
    24 
    25     /**
    26      * 
    27      * @param dataList 集合数据
    28      * @param colNames 表头部数据
    29      * @param mapKey 查找的对应数据
    30      * @param response 返回结果
    31      */
    32     public static boolean doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream os) {
    33         try {
    34             StringBuffer buf = new StringBuffer();
    35 
    36             String[] colNamesArr = null;
    37             String[] mapKeyArr = null;
    38 
    39             colNamesArr = colNames.split(",");
    40             mapKeyArr = mapKey.split(",");
    41 
    42             // 完成数据csv文件的封装
    43             // 输出列头
    44             for (int i = 0; i < colNamesArr.length; i++) {
    45                 buf.append(colNamesArr[i]).append(CSV_COLUMN_SEPARATOR);
    46             }
    47             buf.append(CSV_RN);
    48 
    49             if (null != dataList) { // 输出数据
    50                 for (int i = 0; i < dataList.size(); i++) {
    51                     for (int j = 0; j < mapKeyArr.length; j++) {
    52                         buf.append(dataList.get(i).get(mapKeyArr[j])).append(CSV_COLUMN_SEPARATOR);
    53                     }
    54                     buf.append(CSV_RN);
    55                 }
    56             }
    57             // 写出响应
    58             os.write(buf.toString().getBytes("GBK"));
    59             os.flush();
    60             return true;
    61         } catch (Exception e) {
    62             logger.error("doExport错误...", e);
    63         }
    64         return false;
    65     }
    66 
    67     /**
    68      * @throws UnsupportedEncodingException
    69      * 
    70      *             setHeader
    71      */
    72     public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
    73         // 设置文件后缀
    74         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    75         String fn = fileName + sdf.format(new Date()).toString() + ".csv";
    76         // 读取字符编码
    77         String utf = "UTF-8";
    78 
    79         // 设置响应
    80         response.setContentType("application/ms-txt.numberformat:@");
    81         response.setCharacterEncoding(utf);
    82         response.setHeader("Pragma", "public");
    83         response.setHeader("Cache-Control", "max-age=30");
    84         response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
    85     }
    86 
    87 }

    导出csv 搞定 。 有问题欢迎提问

    偶遇晨光原创

    爱生活,更爱给我带来生活的人
  • 相关阅读:
    C++之友元机制(友元函数和友元类)
    C++之全局函数和成员函数互相转换
    C++之面向对象初探----对象管理模型(关键是this指针)
    C++之const类成员变量,const成员函数
    C++之static类成员,static类成员函数
    c++之函数值传递和引用传递解析----关键在于理解函数return的实现机制(内存分配)
    C++之new和delete
    C++之构造函数、参数列表、析构函数
    C++之匿名对象解析
    C结构体、C++结构体、C++类的区别
  • 原文地址:https://www.cnblogs.com/chenyq/p/5179623.html
Copyright © 2011-2022 走看看