JAVA导出CSV文件

方式一
@GetMapping("/vipExpire/downloadCsv")
    public void downloadCsv(@RequestParam Long taskId, HttpServletResponse response) {
        TaskService vipExpireService = taskServiceMap.get(TaskService.VIP_EXPIRE);
        FileTaskVo fileTask = taskBaseService.getById(taskId);
        List<TaskAplusExpire> list = vipExpireService.search(taskId, TaskAplusExpire.StatusEnum.KO.name());
        log.info("list size = {}",list.size());
        String fileName = fileTask.getFileName().substring(0,fileTask.getFileName().lastIndexOf("."))+"_err_data";

        this.writeCsv(response,fileName,list);
    }




    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = ",";
    /**
     * CSV文件行分隔符
     */
    private static final String CSV_ROW_SEPARATOR = System.lineSeparator();

    private static  final List<String> titleName = Arrays.asList("Pmid","Phone","Send Date","Code","Message");

    /**
     * @param response 响应流
     * @param fileName 文件名称
     * @param dataList  数据源
     */
    private void writeCsv(HttpServletResponse response, String fileName, List<TaskAplusExpire> dataList) {
        OutputStream out = null;
        try {
            StringBuffer buf = new StringBuffer();
            out = response.getOutputStream();
            String lastFileName = fileName + ".csv";
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(lastFileName, "UTF-8"));

            // 组装表头
            for (String title : titleName) {
                buf.append(title).append(CSV_COLUMN_SEPARATOR);
            }
            buf.append(CSV_ROW_SEPARATOR);

            //组装行数据
            dataList.forEach(data->{
                buf.append(Optional.ofNullable(data.getPmid()).orElse("")).append(CSV_COLUMN_SEPARATOR);
                buf.append(Optional.ofNullable(data.getPhone()).orElse("")).append(CSV_COLUMN_SEPARATOR);
                buf.append(DateUtils.format(data.getSendDate())).append(CSV_COLUMN_SEPARATOR);
                buf.append(Optional.ofNullable(data.getCode()).orElse("")).append(CSV_COLUMN_SEPARATOR);
                buf.append(Optional.ofNullable(data.getMessage()).orElse("")).append(CSV_COLUMN_SEPARATOR);
                buf.append(CSV_ROW_SEPARATOR);
            });

            //添加bom,不加Excel打开中文会乱码
            out.write(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF });
            out.write(buf.toString().getBytes("UTF-8"));
        } catch (Exception e) {
           log.error("导出CSV异常",e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    log.error("导出CSV异常",e);
                }
            }
        }
    }
方式二

使用CSVWriter

/**
* @param response 响应流
* @param fileName 文件名称
* @param dataList  数据源
*/
private void writeCsv2(HttpServletResponse response, String fileName, List<TaskAplusExpire> dataList) {
    String lastFileName = fileName + ".csv";
    response.setContentType("application/msexcel;charset=UTF-8");
    try {
        response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(lastFileName, "UTF-8"));
        PrintWriter out = response.getWriter();
        // 手动加上BOM标识
        out.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }));
        
        // 设置显示的顺序,数据源对象属性列表
        String[] columnMapping = { "pmid", "phone", "sendDate", "code", "message" };
       
        ColumnPositionMappingStrategy<TaskAplusExpire> mapper =
            new ColumnPositionMappingStrategy<TaskAplusExpire>();

        //数据源类型
        mapper.setType(TaskAplusExpire.class);
        mapper.setColumnMapping(columnMapping);

        // 写表头
        CSVWriter csvWriter = new CSVWriter(response.getWriter(), CSVWriter.DEFAULT_SEPARATOR,
                                            CSVWriter.NO_QUOTE_CHARACTER);
        String[] header = { "Pmid","Phone","Send Date","Code","Message"};
        csvWriter.writeNext(header);

        StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(out)
            .withMappingStrategy(mapper)
            .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
            .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
            .withEscapechar('\\').build();
        beanToCsv.write(dataList);
        csvWriter.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }catch (CsvDataTypeMismatchException e) {
        e.printStackTrace();
    } catch (CsvRequiredFieldEmptyException e) {
        e.printStackTrace();
    }
Excel打开中文乱码问题

Excel 在读取 csv 的时候是通过读取文件头上的 bom 来识别编码的,这导致如果我们生成 csv 文件的平台输出无 bom 头编码的 csv 文件(例如 utf-8 ,在标准中默认是可以没有 bom 头的),Excel 只能自动按照默认编码读取,不一致就会出现乱码问题了。

解决:
写入的时候加上: out.write(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF });

  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘彦青-Yannis

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值