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

你可能感兴趣的:(java开发笔记,java,开发语言,servlet)