https://blog.csdn.net/fengzyf/article/details/86554106
java 导出csv
导出csv 时候, 遇到中文乱码的问题,最终这一版,解决了问题
下面是导出csv工具类
package com.basetnt.zhilian.coupon.common.util;
import org.apache.commons.collections.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @Desc 导出csv线上版本
* @Date 2019/2/18 16:10
* @Author cui_yl
*/
public class CsvExportUtil {
/**
* CSV文件列分隔符
*/
private static final String CSV_COLUMN_SEPARATOR = ",";
/**
* CSV文件行分隔符
*/
private static final String CSV_ROW_SEPARATOR = System.lineSeparator();
/**
* @param dataList 集合数据
* @param titles 表头部数据
* @param keys 表内容的键值
* @param os 输出流
*/
public static void doExport(List<Map<String, Object>> dataList, String titles, String keys, OutputStream os) throws Exception {
// 保证线程安全
StringBuffer buf = new StringBuffer();
String[] titleArr = null;
String[] keyArr = null;
titleArr = titles.split(",");
keyArr = keys.split(",");
// 组装表头
for (String title : titleArr) {
buf.append(title).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
// 组装数据
if (CollectionUtils.isNotEmpty(dataList)) {
for (Map<String, Object> data : dataList) {
for (String key : keyArr) {
buf.append(data.get(key)).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_ROW_SEPARATOR);
}
}
// 写出响应
os.write(buf.toString().getBytes("GBK"));
os.flush();
}
/**
* 设置Header
*
* @param fileName
* @param response
* @throws UnsupportedEncodingException
*/
public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
// 设置文件后缀
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fn = fileName + sdf.format(new Date()) + ".csv";
// 读取字符编码
String utf = "UTF-8";
// 设置响应
response.setContentType("application/ms-txt.numberformat:@");
response.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
下面是调用
//优惠码管理中导出优惠券
@ApiOperation(value = "优惠码管理中导出优惠券", notes = "优惠码管理中导出优惠券")
@GetMapping(value = "/*****}")
@RequiresRoles(value={"admin", "***", "***"}, logical= Logical.OR)
public void csv(HttpServletResponse response, @PathVariable Integer id, @RequestParam(value = "Token", required = true) String authorization){
try {
// 查询需要导出的数据
CouponForm record = couponService.couponDetail(id);
// 构造导出数据结构
String titles = "id,任务名,优惠券类型,优惠券价值,生效日期,截止日期,优惠码"; // 设置表头
String keys = "id,task,type,price,startTime,endTime,code"; // 设置每列字段
// 构造导出数据
List<Map<String, Object>> datas = new ArrayList<>();
Map<String, Object> map = null;
Coupon coupon = record.getCoupon();
Float price = coupon.getPrice()/100F;
String type = "一次性码";
if (coupon.getType() == CouponType.Common.value()){
type = "通用码";
}
if (null != record && null != coupon){
for (CouponCode data : record.getCodeList()) {
map = new HashMap<>();
map.put("id", coupon.getId());
map.put("task", coupon.getTask());
map.put("type", type);
map.put("price", String.format("%.2f",price));
map.put("startTime", DateUtils.dateToString(coupon.getStartTime(), DateUtils.formatter_yyyyMMdd));
map.put("endTime", DateUtils.dateToString(coupon.getEndTime(), DateUtils.formatter_yyyyMMdd));
map.put("code", data.getCode());
datas.add(map);
}
}
// 设置导出文件前缀
String fName = "优惠券详情_";
// 文件导出
OutputStream os = response.getOutputStream();
CsvExportUtil.responseSetProperties(fName, response);
CsvExportUtil.doExport(datas, titles, keys, os);
os.close();
} catch (Exception e) {
logger.error("导出失败"+e.getMessage(), e);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2019-03-15 springboot框架中-java实现Excel、csv、txt 文件的批量导出数据-亲手实测(一)
---------------------
作者:fengzyf
来源:CSDN
原文:https://blog.csdn.net/fengzyf/article/details/86554106
版权声明:本文为博主原创文章,转载请附上博文链接!