CSV下载工具类

/**
 * csv下载工具类
 */
public class CSVUtils {

    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = ",";
    /**
     * CSV文件列分隔符
     */
    private static final String CSV_RN = "\r\n";

    /**
     * 导出csv格式文件
     * @param data    要导出的数据
     * @param clazz   数据对象类型
     * @param header  表头
     * @param matchColNames 需要匹配的字段名
     * @return
     */
    public static StringBuffer formatCsvInfo(List<?> data, Class<?> clazz, String header, String matchColNames) {
        if (null == data || null == header || null == matchColNames) {
            return null;
        }
        StringBuffer content = new StringBuffer();

        String[] headerArr = header.split(CSV_COLUMN_SEPARATOR);
        String[] matchColNameArr = matchColNames.split(CSV_COLUMN_SEPARATOR);

        // 输出列头
        for (int i = 0; i < headerArr.length; i++) {
            content.append(headerArr[i]);
            content.append(CSV_COLUMN_SEPARATOR);
        }
        content.append(CSV_RN);

        //组装数据
        for (Object obj : data) {
            try {
                for (int i = 0; i < matchColNameArr.length; i++) {
                    String methodName = "get" + matchColNameArr[i].substring(0, 1).toUpperCase() + matchColNameArr[i].substring(1);
                    Object value = clazz.getDeclaredMethod(methodName).invoke(obj);
                    content.append(value);
                    content.append(CSV_COLUMN_SEPARATOR);
                }
                content.append(CSV_RN);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return content;
    }


    /**
     * 导出csv格式文件
     *
     * @param fileName
     * @param content
     * @param response
     * @throws IOException
     */
    public static void exportCsv(String fileName, String content, HttpServletResponse response) throws IOException {
        // 设置文件后缀
        String fn = fileName.concat(".csv");

        // 设置响应
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/csv; charset=UTF-8");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=30");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fn.getBytes(), "UTF-8"));

        // 写出响应
        try(OutputStream os = response.getOutputStream()){
            os.write(content.getBytes("GBK"));
            os.flush();
        }
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值