一、概述

通过 commons-csv 来写入数据并且导出到客户端。

二、引入依赖

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-csv</artifactId>
  4. <version>1.9.0</version>
  5. </dependency>

三、步骤

3.1 写入 csv 数据

  1. public byte[] writeCsv() {
  2. final String[] headerArr = new String[]{"* 编号", "* 收货人姓名", "* 收货地址省份", "*收货地址城市", "* 收货地址区/县", "* 收货详细地址", "* 邮编", "* 固定电话", "* 移动电话", "订单附言", "*配送方式", "外部订单号"};
  3. byte[] bytes = new byte[0];
  4. try {
  5. // 字节数组输出流在内存中创建一个字节数组缓冲区,所有发送到输出流的数据保存在该字节数组缓冲区中。
  6. ByteArrayOutputStream byteArrayOutputStream = null;
  7. byteArrayOutputStream = new ByteArrayOutputStream();
  8. byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
  9. byteArrayOutputStream.write(bom);
  10. // 将输出的字符流变为字节流
  11. OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, StandardCharsets.UTF_8);
  12. // 在写操作期间,字符将被写入内部缓冲区而不是磁盘。 一旦缓冲区被填充或关闭写入器,缓冲区中的所有字符将被写入磁盘。
  13. BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
  14. CSVFormat csvFormat = CSVFormat.DEFAULT;
  15. csvPrinter = new CSVPrinter(bufferedWriter, csvFormat);
  16. // 写入标题
  17. csvPrinter.printRecord(headerArr);
  18. // 写入内容
  19. for (int i = 2; i < 10; i++)
  20. {
  21. csvPrinter.printRecord("userId" + i, "userName" + i);
  22. }
  23. csvPrinter.flush();
  24. bytes = byteArrayOutputStream.toString(StandardCharsets.UTF_8.name()).getBytes();
  25. return bytes;
  26. }catch (IOException e){
  27. e.printStackTrace();
  28. }
  29. return bytes;
  30. }

3.2 设置下载响应

  1. /**
  2. * 设置下载响应
  3. * @param fileName 文件名 eg: abc.csv
  4. * @param bytes 输出流
  5. * @param response 响应报文
  6. */
  7. public void setResponseProperties(String fileName, byte[] bytes, HttpServletResponse response) {
  8. try {
  9. // 设置编码格式
  10. fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
  11. response.setContentType("application/csv");
  12. response.setCharacterEncoding(StandardCharsets.UTF_8.name());
  13. response.setHeader("Pragma", "public");
  14. response.setHeader("Cache-Control", "max-age=30");
  15. response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
  16. OutputStream outputStream = response.getOutputStream();
  17. outputStream.write(bytes);
  18. outputStream.flush();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }