将el-table数据导出csv各式,纯前端实现

复制代码
 tableData数据:

 tableData: [

        { column1: '值1-1', column2: '值1-2' },

        { column1: '值2-1', column2: '值2-2' },

        { column1: '值3-1', column2: '值3-2' }

      ],  

 exportToCSV() {
      // 将表格数据转化为CSV格式
      const csvContent = this.convertArrayOfObjectsToCSV(this.tableData);
      // 创建下载链接,用于下载生成的CSV文件
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', 'data.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    convertArrayOfObjectsToCSV(data) {
      const csvRows = [];
      const headers = Object.keys(data[0]);
      console.log('headers',headers);

      // 添加表头
      csvRows.push(headers.join(','));
         
      // 添加表格数据
      for (const row of data) {
        const values = headers.map(header => {
          const escapeQuotes = row[header]
          return `"${escapeQuotes}"`;
        });
        csvRows.push(values.join(','));
      }

      // 返回CSV内容
      return csvRows.join('\n');
    },

结果如下:

如果想要将表头替换为文字,可以重新遍历循环tableData,例如将【column1】转化为【第一列】

复制代码
   exportToCSV() {
      // 将表格数据转化为CSV格式
         const keyMapping = {
                column1: '第一列',
            }
        const modifiedTableData =[]
          this.tableDatas.map(obj => {
            const modifiedObj = {};
            for (let key in obj) {
                if (keyMapping.hasOwnProperty(key)) {
                const newKey = keyMapping[key];
                modifiedObj[newKey] = obj[key];
                } else {
                modifiedObj[key] = obj[key];
                }
            }
            modifiedTableData.push(modifiedObj)
            });
      const csvContent = this.convertArrayOfObjectsToCSV(modifiedTableData);
      // 创建下载链接,用于下载生成的CSV文件
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', 'data.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    convertArrayOfObjectsToCSV(data) {
      const csvRows = [];
      const headers = Object.keys(data[0]);
      console.log('headers',headers);

      // 添加表头
      csvRows.push(headers.join(','));
         
      // 添加表格数据
      for (const row of data) {
        const values = headers.map(header => {
          const escapeQuotes = row[header]
          return `"${escapeQuotes}"`;
        });
        csvRows.push(values.join(','));
      }

      // 返回CSV内容
      return csvRows.join('\n');
    },

效果图:

方法二:

使用json2csv 插件

复制代码
npm install json2csv

引入到页面

import json2csv from 'json2csv'

使用: 将 modifiedTableData 替换成自己的table表格数据即可

复制代码
downLoadList = [
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 1,
        "role_id": "37974710003",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 2,
        "role_id": "901610410087",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 3,
        "role_id": "13905284310012",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 4,
        "role_id": "880304610074",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 5,
        "role_id": "6801495710100",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 6,
        "role_id": "1270134610085",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 7,
        "role_id": "20562212610019",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 8,
        "role_id": "62620815003",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 9,
        "role_id": "20562307510100",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 10,
        "role_id": "6720994815049",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 11,
        "role_id": "904776310079",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 12,
        "role_id": "459012010070",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 13,
        "role_id": "8005578310049",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 14,
        "role_id": "7197854010103",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 15,
        "role_id": "7168183615042",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 16,
        "role_id": "7589462510011",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 17,
        "role_id": "21012727610067",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 18,
        "role_id": "13489399910050",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 19,
        "role_id": "13854480410040",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 20,
        "role_id": "10089315001",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 21,
        "role_id": "65930410095",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": null,
        "row_index": 22,
        "role_id": "876720810048",
        "type": "false"
    },
    {
        "info_sql": "",
        "error_key": "[214002]",
        "reason": -1,
        "row_index": 0,
        "role_id": "875358210085",
        "type": "false"
    }
]  
exportToCSV() {
            // 转化错误原因
            //downLoadList.map(item => {
              // this.reasonList.map(val => {
                // if(item.reason === val.id) {
                  //  item.reason = val.reason
                 //}
               //})
            //})
            // 将对应的key值转化为文字
            const keyMapping = {
                row_index: '报错序号',
                reason: '报错原因',
                abnormal_mark:'异常检测标记',
                threshold:'异常阈值标记',
                sql:'查询sql语句'
            }
            const modifiedTableData =[]
            downLoadList.map(obj => {
            const modifiedObj = {};
            for (let key in obj) {
                if (keyMapping.hasOwnProperty(key)) {
                const newKey = keyMapping[key];
                modifiedObj[newKey] = obj[key];
                } else {
                modifiedObj[key] = obj[key];
                }
            }
            modifiedTableData.push(modifiedObj)
            });
           let list = modifiedTableData[0]
            const fields = Object.keys(list) // 与表格列定义一致,用于设置表头
            const csvData = json2csv.parse( modifiedTableData, { fields }); // 将 el-table 数据转换为 CSV 字符串
            const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' }); // 创建Blob对象
            const url = URL.createObjectURL(blob); // 创建 Blob URL
            const link = document.createElement('a'); // 创建下载链接
            link.href = url;
            link.setAttribute('download', '执行结果.csv'); // 设置文件名
            document.body.appendChild(link);
            link.click();

            document.body.removeChild(link); // 移除下载链接
            URL.revokeObjectURL(url); // 释放 Blob URL
        },
相关推荐
biu_biubiu22 分钟前
我开源了 Codebook
前端·vue.js
下山23 分钟前
怎么把带自研插件的 DeepSeek Harness 部署到云服务器
前端
彭亚川Allen30 分钟前
985 在职研究生到底怎么样?是不是水硕?是不是.....?
前端·后端·程序员
YufJi32 分钟前
两棵树,两个线程:一个小程序引擎的架构拆解
前端
super_Omni42 分钟前
Chrome 插件入驻实战:从 Manifest V3 到过审上架的完整路径
大数据·前端·chrome
腾讯数据架构师1 小时前
任务跑完怎么直接出图表?CubeStudio 任务可视化 ECharts 数据格式实操(CSV/JSON + metric.json,11 种图表一键渲染)
前端·json·echarts·数据可视化
小小小米粒1 小时前
不是在构造方法「之前」修饰 Bean、注入;是构造方法跑完之后,才做属性注入,再跑 @PostConstruct。
前端
小李科技1 小时前
【性能优化】事件委托:目标定位与 React/Vue 实战
前端·vue.js·react.js·面试·性能优化·前端框架
QianhangQianping2 小时前
一块大屏的数据在浏览器里怎么变成画面:背景、子屏、前景三层结构
前端·低代码·架构·编辑器·数据可视化·大屏可视化
梦想很大很大2 小时前
让 Codex 自由发挥,给 nvm-desktop 换个 UI
前端·人工智能·设计