springboot 导出CSV

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> 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 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));
    }

}

下面是调用

    //优惠码管理中导出优惠券
    @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> datas = new ArrayList<>();
            Map 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);
        }
    }

你可能感兴趣的:(java技术点)