springMVC导出 CSV案例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = "\r\n";
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 搞定 。 有问题欢迎提问

偶遇晨光原创

 

以上是关于springMVC导出 CSV案例的主要内容,如果未能解决你的问题,请参考以下文章

使用html代码将mysql表导出到csv

如何修复此代码,我没有收到错误,但数据未导出到 csv

java里将从excel读到的数据用csv导出,代码怎么写

SQL、PHP 导出为 CSV

如何导出csv nodejs

从Wordpress导出CSV |文件中的源代码?