java springboot 导出文件到csv

优点:可以大数据量导出,效率快

一、

public void exportExcel() throws Exception {
//1、查询数据
List> list = baseMapper.exportCsv();
//如果需要对查出来的数据进行处理,可以新建List,遍历查询结果,处理完后添加到List
//List> dataList = new ArrayList<>();
//Map map = null;
//for (Data data : list ) {
//map = new HashMap<>();
//map.put("userName", data.getUserName());
//map.put("name", data.getName());
//dataList.add(map);
//}
//2、构造导出数据结构
   String titles = "用户,名称";  // 设置表头
   String keys = "userName,name";  // 设置每列字段
//3、 文件导出
   OutputStream os = response.getOutputStream();
   CsvExportUtil.responseSetProperties("", response);
   CsvExportUtil.doExport(list, titles, keys, os);
   //CsvExportUtil.doExport(dataList , titles, keys, os);
   os.close();
}

二、导出csv工具类

package org.common.utils;

import org.apache.commons.collections.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @Desc 导出csv线上版本
 * @Date 2019/2/18 16:10
 * @Author cui_yl
 */
public class CsvExportUtil {
   /**
    * CSV文件列分隔符
    */
   private static final String CSV_COLUMN_SEPARATOR = ",";

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

   /**
    * @param dataList 集合数据
    * @param titles   表头部数据
    * @param keys     表内容的键值
    * @param os       输出流
    */
   public static void doExport(List> dataList, String titles, String keys, OutputStream os) throws Exception {
      // 保证线程安全
      StringBuffer buf = new StringBuffer();

      String[] titleArr = null;
      String[] keyArr = null;

      titleArr = titles.split(",");
      keyArr = keys.split(",");

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

      // 组装数据
      if (CollectionUtils.isNotEmpty(dataList)) {
         for (Map data : dataList) {
            for (String key : keyArr) {
               buf.append("\t"+(data.get(key)!=null?data.get(key)+"":"")+"\t").append(CSV_COLUMN_SEPARATOR);
            }
            buf.append(CSV_ROW_SEPARATOR);
         }
      }

      // 写出响应
      os.write(buf.toString().getBytes("GBK"));
      os.flush();
   }

   /**
    * 设置Header
    *
    * @param fileName
    * @param response
    * @throws UnsupportedEncodingException
    */
   public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
      // 设置文件后缀
      String fn = fileName + DateUtils.getCurrentDateTimeYMDHMS() + ".csv";
      // 读取字符编码
      String utf = "UTF-8";

      // 设置响应
      response.setContentType("application/ms-txt.numberformat:@");
      response.setCharacterEncoding(utf);
      response.setHeader("Pragma", "public");
      response.setHeader("Cache-Control", "max-age=30");
      response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
   }

}

你可能感兴趣的:(工具类,java,csv,excel)