Java 导出 csv 文件

    /**
     * @param response 响应流
     * @param fields
     * @param dataList 数据源
     */
    private static void writeCSV(HttpServletResponse response, List<SqlFieldVO> fields, List<Map<String, Object>> dataList) {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = "SQLResult" + df.format(new Date()) + ".csv";
        OutputStream out = null;
        CSVWriter writer = null;
        try {
            // 设置响应头,指定文件类型为CSV
            response.setContentType("text/csv");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 创建CSVWriter对象 将其连接到响应的OutputStream
            out = response.getOutputStream();
            out.write(new byte []{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            writer = new CSVWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));


            // 写入表头
            String[] header = fields.stream().map(vo -> {
                String name = vo.getFieldCode();
                if (vo.getFieldTitle() != null && !Objects.equals(vo.getFieldTitle(), "")) {
                    name = vo.getFieldTitle();
                }
                return name;
            }).toArray(String[]::new);
            writer.writeNext(header);
            // 写入数据
            for (Map<String, Object> map : dataList) {
                List<String> tempList = new ArrayList<>();
                fields.stream().forEach(field ->{
                    tempList.add(map.get(field.getFieldCode()) == null ? "" : map.get(field.getFieldCode()).toString());
                });
                writer.writeNext(tempList.toArray(new String[0]));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值