前端导出csv

697 阅读1分钟

前端导出csv,导出带有分页的全部数据。使用aggrid ,exportDataAsCsv 只能导出当前页,不能导出全部分页数据。使用xlsx, 数字会转化成科学计数法。自己封装导出csv如下:


import React from "react";
import { Button } from "antd";

const res = {
  totalCount: 2,
  page: [
    {
      parentFundAccount: "202201010010010001",
      tradeNode: "SH",
      orderId: "2022010100987",
      orderStatus: "delay",
      standStillTime: 12225566669999,
    },
    {
      parentFundAccount: "202201010010010002",
      tradeNode: "SH",
      orderId: "2022010100988",
      orderStatus: "reject",
      standStillTime: 12225566668000,
    },
  ],
};

const headers = [
  "资金账号",
  "交易节点",
  "订单编号",
  "订单当前状态",
  "时延时间(毫秒)",
];

const csvExport = (obj: any) => {
  //处理数据
  const title = obj?.title;
  const data = obj?.data;
  let str: string[] = [];
  str.push(title.join(",") + "\r\n");
  if (data?.length) {
    for (let i = 0; i < data?.length; i++) {
      let temp = [];
      const dataKey = Object.keys(data[i]);
      for (let j = 0; j < dataKey.length; j++) {
        const value = data[i][dataKey[j]];
        if (value) {
          // csv导出 如果数字大于12位,会自动转化为科学计数法,为避免转化科学计数法,转化成String。
          temp.push(`${value}\t`);
        } else {
          temp.push(undefined);
        }
      }
      str.push(temp.join(",") + "\r\n");
    }
  }
  const blob = new Blob(["\uFEFF" + str.join("")], {
    type: "text/csv;charset=utf-8",
  });
  //导出
  const url = window.URL.createObjectURL(blob);
  const downloadLink = document.createElement("a");
  downloadLink.href = url;
  downloadLink.download = obj.fileName;
  downloadLink.click();
  window.URL.revokeObjectURL(url);
};

const ExportButton = () => {
  return (
    <Button
      type="primary"
      style={{ marginBottom: 10 }}
      onClick={() => {
        // data 和 headers 的字段顺序需一一对应,否则会乱序。
        csvExport({
          title: headers,
          data: res?.page,
          fileName: `导出.csv`,
        });
      }}
    >
      导出
    </Button>
  );
};

export default ExportButton;