csv文件导出

/**
   * CSV文件列分隔符
   */
  private static final String CSV_COLUMN_SEPARATOR = ",";

  /**
   * CSV文件行分隔符
   */
  private static final String CSV_ROW_SEPARATOR = "\r\n";

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

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

    // 组装数据
    if (CollectionUtils.isNotEmpty(dataList)) {
      for (Map<String, Object> data : dataList) {
        Set<String> strings = data.keySet();
        for (String key : strings) {
          Object o = data.get(key);
          if (o.getClass().equals(Date.class)){
            o = simpleDateFormat.format(o);
            buf.append("\t"+o+"\t").append(CSV_COLUMN_SEPARATOR);
            continue;
          }
          buf.append(o).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 {
    // 设置文件后缀
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    String fn = fileName + sdf.format(new Date()) + ".csv";
    // 读取字符编码
    String utf = "UTF-8";

    // 设置响应
    response.setCharacterEncoding(utf);
    response.setHeader("Pragma", "public");
    response.setHeader("Cache-Control", "max-age=30");
    try {
      response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值