前言

最近的项目遇到一个需求,导出table表格数据,在网上搜了一下资料有几种方式可以实现,最快速的方法是让后端处理好数据,奈何一些原因只能前端自己来转了~


一、前期准备

下载插件

npm i xlxs //表格文件的插件
npm i file-saver //保存文件的插件

src目录下新建excel文件夹,并新建文件Excel2json.js文件(可以直接在网上找到这个文件,下面将我使用的代码文件贴出供大家参考)

/* eslint-disable */
// 1:下载  file-saver    xlsx,如果出现问题,如果以前是yarn,先执行yarn  如果还不行,再执行npm i 再运行,如果还不行自行调整版本 yarn add 插件名@版本号
//  
// 文件下载生成
import { saveAs } from 'file-saver'
// 生成excel与解析excel数据
import XLSX from 'xlsx'

function generateArray(table) {
  var out = [];
  var rows = table.querySelectorAll('tr');
  var ranges = [];
  for (var R = 0; R < rows.length; ++R) {
    var outRow = [];
    var row = rows[R];
    var columns = row.querySelectorAll('td');
    for (var C = 0; C < columns.length; ++C) {
      var cell = columns[C];
      var colspan = cell.getAttribute('colspan');
      var rowspan = cell.getAttribute('rowspan');
      var cellValue = cell.innerText;
      if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;

      //Skip ranges
      ranges.forEach(function (range) {
        if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
          for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
        }
      });

      //Handle Row Span
      if (rowspan || colspan) {
        rowspan = rowspan || 1;
        colspan = colspan || 1;
        ranges.push({
          s: {
            r: R,
            c: outRow.length
          },
          e: {
            r: R + rowspan - 1,
            c: outRow.length + colspan - 1
          }
        });
      };

      //Handle Value
      outRow.push(cellValue !== "" ? cellValue : null);

      //Handle Colspan
      if (colspan)
        for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
    }
    out.push(outRow);
  }
  return [out, ranges];
};

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
  var ws = {};
  var range = {
    s: {
      c: 10000000,
      r: 10000000
    },
    e: {
      c: 0,
      r: 0
    }
  };
  for (var R = 0; R != data.length; ++R) {
    for (var C = 0; C != data[R].length; ++C) {
      if (range.s.r > R) range.s.r = R;
      if (range.s.c > C) range.s.c = C;
      if (range.e.r < R) range.e.r = R;
      if (range.e.c < C) range.e.c = C;
      var cell = {
        v: data[R][C]
      };
      if (cell.v == null) continue;
      var cell_ref = XLSX.utils.encode_cell({
        c: C,
        r: R
      });

      if (typeof cell.v === 'number') cell.t = 'n';
      else if (typeof cell.v === 'boolean') cell.t = 'b';
      else if (cell.v instanceof Date) {
        cell.t = 'n';
        cell.z = XLSX.SSF._table[14];
        cell.v = datenum(cell.v);
      } else cell.t = 's';

      ws[cell_ref] = cell;
    }
  }
  if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
  return ws;
}

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  this.Sheets = {};
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

export function export_table_to_excel(id) {
  var theTable = document.getElementById(id);
  var oo = generateArray(theTable);
  var ranges = oo[1];

  /* original data */
  var data = oo[0];
  var ws_name = "SheetJS";

  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  /* add ranges to worksheet */
  // ws['!cols'] = ['apple', 'banan'];
  ws['!merges'] = ranges;

  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  });

  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), "test.xlsx")
}
// 将json数据转换成excel并提供下载
// header:头部  ['姓名','转正时间'...]
// data:列表数据  [['张三',‘2021-12-01’...]]
// filename:下载的文件名,默认是excel-list
export function export_json_to_excel({
  multiHeader = [],
  header,
  data,
  filename,
  merges = [],
  autoWidth = true,
  bookType = 'xlsx'
} = {}) {
  /* original data */
  filename = filename || 'excel-list'
  data = [...data]
  data.unshift(header);

  for (let i = multiHeader.length - 1; i > -1; i--) {
    data.unshift(multiHeader[i])
  }

  var ws_name = "SheetJS";
  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  if (merges.length > 0) {
    if (!ws['!merges']) ws['!merges'] = [];
    merges.forEach(item => {
      ws['!merges'].push(XLSX.utils.decode_range(item))
    })
  }

  if (autoWidth) {
    /*设置worksheet每列的最大宽度*/
    const colWidth = data.map(row => row.map(val => {
      /*先判断是否为null/undefined*/
      if (val == null) {
        return {
          'wch': 10
        };
      }
      /*再判断是否为中文*/
      else if (val.toString().charCodeAt(0) > 255) {
        return {
          'wch': val.toString().length * 2
        };
      } else {
        return {
          'wch': val.toString().length
        };
      }
    }))
    /*以第一行为初始值*/
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
      for (let j = 0; j < colWidth[i].length; j++) {
        if (result[j]['wch'] < colWidth[i][j]['wch']) {
          result[j]['wch'] = colWidth[i][j]['wch'];
        }
      }
    }
    ws['!cols'] = result;
  }

  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  var wbout = XLSX.write(wb, {
    bookType: bookType,
    bookSST: false,
    type: 'binary'
  });
  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), `${filename}.${bookType}`);
}

二、使用步骤

上面的准备工作做好了就可以引入使用啦~

1.最基本的表格导出样式

在这里我直接使用的是获取全部的接口返回数据处理的,代码如下:

<el-button type="primary" style="margin-right:10px" @click="exportExcel" icon="el-icon-download">导出</el-button>

接下来在页面中引入Excel2json.js中的转换方法

import { export_json_to_excel } from '@/vendor/Export2Excel'

到这里就直接是导出的方法

 // 表格数据导出
    async exportExcel() {
      const data = {
        pageNo: 1,
        pageSize: 9999, //给定页面一个最大值,用于获取所有分页数据
      }
      const res = await queryList(data)
      // console.log(res, 'res全部数据');
      // 写好数据转换的规则
      //这个地方写的是需要导出的表头以及表头对应的字段
      const rules = {
        '注册时间': 'date',
        '用户名称': 'name',
        '邮箱': 'email',
        '手机号': 'phone',
        '角色': 'role',
        '类型': 'type',
        '状态': 'status'
      }
      const newArr = res.data.records.map(item => {
        const arr = []
        Object.values(rules).forEach(item2 => {
          arr.push(item[item2])
        })
        return arr
      })
      export_json_to_excel({
        header: Object.keys(rules),
        data: newArr,
        filename: 'xxx文件'
      })
    }

导出的文件格式如下:

在这里插入图片描述

2.在基本的基础上加了一些样式

第一次导出来的表格是最基础的,没有什么样式,被砍下来了,所以第二次做了一些样式上面的处理,加了表头标题,表头备注项,以及单元格边框,处理的可能并没有很好,如果有更好的处理方式可以留言让我学习😁

在这里下载了一个插件xlxs-style

npm i xlxs-style

下载完成之后控制台报错xlsx-style ./cptable,这是不用慌,有两种方式解决

第一种,直接修改\node_modules\xlsx-style\dist\cpexcel.js源文件,打开文件找到807行

var cpt = require('./cpt' + 'able');  
改为 var cpt = cptable;

第二种,直接修改vue.config.js配置文件

chainWebpack: config => {
        config.externals({ './cptable': 'var cptable' })
    }

这里记录一下我遇到的问题!!!

我最开始是采用的第一种方法,在开发的分支上面没有问题,但是当我把代码推到另外一个分支的时候,打包项目时出问题了,报错信息就是找不到\node_modules\xlsx-style\dist\cpexcel.js这个文件!

在网上搜了一下看到了一位博主贴出的第二种方法,于是试了一下,成功了!!!也没有报错~

所以在这里推荐大家使用第二种直接修改配置文件

接下来就是更改样式了,直接在Excel2json.js文件里面进行修改,上代码!!!

/* eslint-disable */
require('script-loader!file-saver');
require('./Blob.js');//这里是你的Blob.js的地址
require('script-loader!xlsx/dist/xlsx.core.min');
import XLSX from "xlsx-style" //必须要引入才可以,否则报错

function generateArray(table) {
  var out = [];
  var rows = table.querySelectorAll('tr');
  var ranges = [];
  for (var R = 0; R < rows.length; ++R) {
    var outRow = [];
    var row = rows[R];
    var columns = row.querySelectorAll('td');
    for (var C = 0; C < columns.length; ++C) {
      var cell = columns[C];
      var colspan = cell.getAttribute('colspan');
      var rowspan = cell.getAttribute('rowspan');
      var cellValue = cell.innerText;
      if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;

      //Skip ranges
      ranges.forEach(function (range) {
        if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
          for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
        }
      });
      //Handle Row Span
      if (rowspan || colspan) {
        rowspan = rowspan || 1;
        colspan = colspan || 1;
        ranges.push({
          s: {
            r: R,
            c: outRow.length
          },
          e: {
            r: R + rowspan - 1,
            c: outRow.length + colspan - 1
          }
        });
      }
      ;

      //Handle Value
      outRow.push(cellValue !== "" ? cellValue : null);

      //Handle Colspan
      if (colspan)
        for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
    }
    out.push(outRow);
  }
  return [out, ranges];
};

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
  var ws = {};
  var range = {
    s: {
      c: 10000000,
      r: 10000000
    },
    e: {
      c: 0,
      r: 0
    }
  };
  for (var R = 0; R != data.length; ++R) {
    for (var C = 0; C != data[R].length; ++C) {
      if (range.s.r > R) range.s.r = R;
      if (range.s.c > C) range.s.c = C;
      if (range.e.r < R) range.e.r = R;
      if (range.e.c < C) range.e.c = C;
      var cell = {
        v: data[R][C]
      };
      // if (cell.v == null) continue;
      //如果接口数据有返回null的,统一替换成为''进行展示
      if(data[R][C] == null){
        cell={
          v:''
        }
      }
      var cell_ref = XLSX.utils.encode_cell({
        c: C,
        r: R
      });

      if (typeof cell.v === 'number') cell.t = 'n';
      else if (typeof cell.v === 'boolean') cell.t = 'b';
      else if (cell.v instanceof Date) {
        cell.t = 'n';
        cell.z = XLSX.SSF._table[14];
        cell.v = datenum(cell.v);
      } else cell.t = 's';

      ws[cell_ref] = cell;
    }
  }
  if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
  return ws;
}

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  this.Sheets = {};
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

export function export_table_to_excel(id) {
  var theTable = document.getElementById(id);
  var oo = generateArray(theTable);
  var ranges = oo[1];
  /* original data */
  var data = oo[0];
  var ws_name = "SheetJS";

  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  /* add ranges to worksheet */
  // ws['!cols'] = ['apple', 'banan'];
  ws['!merges'] = ranges;
  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  });

  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), "test.xlsx")
}

export function export_json_to_excel({
                                       multiHeader = [],
                                       multiHeader2 = [],
                                       header,
                                       data,
                                       filename,
                                       merges = [],
                                       autoWidth = true,
                                       bookType = 'xlsx'
                                     } = {}) {
  /* original data */
  filename = filename || 'excel-list'
  data = [...data]
  data.unshift(header);
  for (let i = multiHeader.length - 1; i > -1; i--) {
    data.unshift(multiHeader[i])
  }

  for (let i = multiHeader2.length - 1; i > -1; i--) {
    data.unshift(multiHeader2[i])
  }

  var ws_name = "SheetJS";
  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  if (merges.length > 0) {
    if (!ws['!merges']) ws['!merges'] = [];
    merges.forEach(item => {
      ws['!merges'].push(XLSX.utils.decode_range(item))
    })
  }

  if (autoWidth) {
    /*设置worksheet每列的最大宽度*/
    const colWidth = data.map(row => row.map(val => {
      /*先判断是否为null/undefined*/
      if (val == null) {
        return {
          'wch': 10
        };
      }
      /*再判断是否为中文*/
      else if (val.toString().charCodeAt(0) > 255) {
        return {
          // 'wch': val.toString().length * 2
          'wch': 10
        };
      } else {
        return {
          'wch': val.toString().length
        };
      }
    }))
    /*以第一行为初始值*/
    // 以第二行为初始值,因为第一行是标题,第二行是备注项
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
      for (let j = 0; j < colWidth[i].length; j++) {
        if (result[j]['wch'] < colWidth[i][j]['wch']) {
          result[j]['wch'] = colWidth[i][j]['wch'];
        }
      }
    }
    ws['!cols'] = result;
  }

  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  // 获取工作簿
  var dataInfo = wb.Sheets[wb.SheetNames[0]];
    // 设置单元格框线
  const borderAll = {
    top: {
      style: "thin",
      color:{
        rgb:'#c3cbdd'
      }
    },
    bottom: {
      style: "thin",
      color:{
        rgb:'#c3cbdd'
      }
    },
    left: {
      style: "thin",
      color:{
        rgb:'#c3cbdd'
      }
    },
    right: {
      style: "thin",
      color:{
        rgb:'#c3cbdd'
      }
    }
  };
  
  // 给所有单元格加上边框,内容居中,字体,字号,标题表头特殊格式部分后面替换
  for (var i in dataInfo) {
    if (
      i == "!ref" ||
      i == "!merges" ||
      i == "!cols" ||
      i == "!rows" ||
      i == "A1"
    ) { } else {
      dataInfo[i + ""].s = {
        border: borderAll,
        alignment: {
          // 自动换行
          wrapText: 1,
          horizontal: "center",
          vertical: "center"
        },
        font: {
          name: "宋体",
          sz: 10
        }
      };
    }
  }
  
  // 设置表格样式
  const arrabc = ["A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z"
  ]
  
  // 给标题、表格描述信息、表头等部分加上特殊格式
  arrabc.some(function (v) {
    for (let j = 1; j < multiHeader.length + 3; j++) {
      const _v = v + j
      if (dataInfo[_v]) {
        dataInfo[_v].s = {};
        // 标题部分A1-Z1
        if (j == 1) {
          dataInfo[v + j].s = {
            font: {
              name: "宋体",
              sz: 12,
              color: {
                rgb: "000000"
              },
              bold: true,
              italic: false,
              underline: false
            },
            alignment: {
              wrapText: 1,
              horizontal: "center",
              vertical: "center"
            }
          };
        } else {
        // 表头部分,根据表头特殊格式设置
          if (multiHeader.length == 0) {
          // multiHeader.length = 0 时表头没有合并单元格,表头只占1行A2-Z2
            const fv = v + (multiHeader.length + 2)
            dataInfo[fv].s = {
              border: borderAll,
              font: {
                name: "宋体",
                sz: 11,
                bold: true
              },
              alignment: {
                wrapText: 1,
                horizontal: "center",
                vertical: "center"
              },
              // fill: {
              //   fgColor: {
              //     rgb: "f0f0f0"
              //   },
              // },
            }
          } else if (multiHeader.length == 1) {
          // multiHeader.length = 0 时表头有合并单元格,表头只占2行A2-Z2,A3-Z3,这是没有描述信息只有表头合并的
            dataInfo[v + j].s = {
              border: borderAll,
              font: {
                name: "宋体",
                sz: 9,
              },
              alignment: {
                wrapText: 1,
                horizontal: "left",
                vertical: "center"
              },
              // fill: {
              //   fgColor: {
              //     rgb: "f0f0f0"
              //   }
              // },
            }
          } else {
           // multiHeader.length = 0 时表头有合并单元格,表头多行
            dataInfo[v + j].s = {
              border: borderAll,
              font: {
                name: "宋体",
                sz: 9,
              },
              alignment: {
                wrapText: 1,
                horizontal: "left",
                vertical: "center"
              }
            }
          }
        }
        // multiHeader.length + 2 是表头的最后1行
        dataInfo[v + (multiHeader.length + 2)].s = {
          border: borderAll,
          font: {
            name: "宋体",
            sz: 10,
          },
          alignment: {
            wrapText: 1,
            horizontal: "center",
            vertical: "center"
          },
          fill: {
            fgColor: {
              rgb: "f0f0f0"
            }
          },
        }
      }
    }
  });

  var wbout = XLSX.write(wb, {
    bookType: bookType,
    bookSST: false,
    type: 'binary'
  });
  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), `${filename}.${bookType}`);
}

别忘了还有一个文件Blob.js,直接复制使用

/* eslint-disable */
/* Blob.js
 * A Blob implementation.
 * 2014-05-27
 *
 * By Eli Grey, http://eligrey.com
 * By Devin Samarin, https://github.com/eboyjr
 * License: X11/MIT
 *   See LICENSE.md
 */
/*global self, unescape */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
 plusplus: true */
/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
(function (view) {
    "use strict";
    view.URL = view.URL || view.webkitURL;
    if (view.Blob && view.URL) {
      try {
        new Blob;
        return;
      } catch (e) {}
    }
    // Internally we use a BlobBuilder implementation to base Blob off of
    // in order to support older browsers that only have BlobBuilder
    var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
      var
        get_class = function(object) {
          return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
        }
        , FakeBlobBuilder = function BlobBuilder() {
          this.data = [];
        }
        , FakeBlob = function Blob(data, type, encoding) {
          this.data = data;
          this.size = data.length;
          this.type = type;
          this.encoding = encoding;
        }
        , FBB_proto = FakeBlobBuilder.prototype
        , FB_proto = FakeBlob.prototype
        , FileReaderSync = view.FileReaderSync
        , FileException = function(type) {
          this.code = this[this.name = type];
        }
        , file_ex_codes = (
          "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
          + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
        ).split(" ")
        , file_ex_code = file_ex_codes.length
        , real_URL = view.URL || view.webkitURL || view
        , real_create_object_URL = real_URL.createObjectURL
        , real_revoke_object_URL = real_URL.revokeObjectURL
        , URL = real_URL
        , btoa = view.btoa
        , atob = view.atob
        , ArrayBuffer = view.ArrayBuffer
        , Uint8Array = view.Uint8Array
      ;
      FakeBlob.fake = FB_proto.fake = true;
      while (file_ex_code--) {
        FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
      }
      if (!real_URL.createObjectURL) {
        URL = view.URL = {};
      }
      URL.createObjectURL = function(blob) {
        var
          type = blob.type
          , data_URI_header
        ;
        if (type === null) {
          type = "application/octet-stream";
        }
        if (blob instanceof FakeBlob) {
          data_URI_header = "data:" + type;
          if (blob.encoding === "base64") {
            return data_URI_header + ";base64," + blob.data;
          } else if (blob.encoding === "URI") {
            return data_URI_header + "," + decodeURIComponent(blob.data);
          } if (btoa) {
            return data_URI_header + ";base64," + btoa(blob.data);
          } else {
            return data_URI_header + "," + encodeURIComponent(blob.data);
          }
        } else if (real_create_object_URL) {
          return real_create_object_URL.call(real_URL, blob);
        }
      };
      URL.revokeObjectURL = function(object_URL) {
        if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
          real_revoke_object_URL.call(real_URL, object_URL);
        }
      };
      FBB_proto.append = function(data/*, endings*/) {
        var bb = this.data;
        // decode data to a binary string
        if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
          var
            str = ""
            , buf = new Uint8Array(data)
            , i = 0
            , buf_len = buf.length
          ;
          for (; i < buf_len; i++) {
            str += String.fromCharCode(buf[i]);
          }
          bb.push(str);
        } else if (get_class(data) === "Blob" || get_class(data) === "File") {
          if (FileReaderSync) {
            var fr = new FileReaderSync;
            bb.push(fr.readAsBinaryString(data));
          } else {
            // async FileReader won't work as BlobBuilder is sync
            throw new FileException("NOT_READABLE_ERR");
          }
        } else if (data instanceof FakeBlob) {
          if (data.encoding === "base64" && atob) {
            bb.push(atob(data.data));
          } else if (data.encoding === "URI") {
            bb.push(decodeURIComponent(data.data));
          } else if (data.encoding === "raw") {
            bb.push(data.data);
          }
        } else {
          if (typeof data !== "string") {
            data += ""; // convert unsupported types to strings
          }
          // decode UTF-16 to binary string
          bb.push(unescape(encodeURIComponent(data)));
        }
      };
      FBB_proto.getBlob = function(type) {
        if (!arguments.length) {
          type = null;
        }
        return new FakeBlob(this.data.join(""), type, "raw");
      };
      FBB_proto.toString = function() {
        return "[object BlobBuilder]";
      };
      FB_proto.slice = function(start, end, type) {
        var args = arguments.length;
        if (args < 3) {
          type = null;
        }
        return new FakeBlob(
          this.data.slice(start, args > 1 ? end : this.data.length)
          , type
          , this.encoding
        );
      };
      FB_proto.toString = function() {
        return "[object Blob]";
      };
      FB_proto.close = function() {
        this.size = this.data.length = 0;
      };
      return FakeBlobBuilder;
    }(view));
    view.Blob = function Blob(blobParts, options) {
      var type = options ? (options.type || "") : "";
      var builder = new BlobBuilder();
      if (blobParts) {
        for (var i = 0, len = blobParts.length; i < len; i++) {
          builder.append(blobParts[i]);
        }
      }
      return builder.getBlob(type);
    };
  }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));
  
  

上面的步骤完成之后,将调用的方法进行一些更改

    // 表格数据导出
    async exportExcel() {
      const data = {
        pageNo: 1,
        pageSize: 999,
        hideNonCommercial: this.checked === true ? 1 : 0,
        roleCode: this.search.status !== 'all' ? this.search.status : null,
        column: this.search.keyword,
        value: this.search.value
      }
      const res = await queryList(data)
      // console.log(res, 'res全部数据');
      // return
      //备注项这里是一个二维数组,没有内容的部分使用''占位
      //表头标题部分做同样的处理
      const multiHeader = [['备注:类型-1:xx 2:xx 3:xx 4:xx', '', '', '', '', '', '', ''], ['状态-1:xx 0:xx', '', '', '', '', '', '', '']]
      const multiHeader2 = [['xxx表格', '', '', '', '', '', '', '']]
      //合并单元格
      const merges = ['A1:H1', 'A2:H2', 'A3:H3']
      // 写好数据转换的规则
      const rules = {
        '注册时间': 'date',
        '用户名称': 'name',
        '邮箱': 'email',
        '手机号': 'phone',
        '角色': 'role',
        '类型': 'type',
        '状态': 'status'
      }

      const newArr = res.data.records.map(item => {
        const arr = []
        Object.values(rules).forEach(item2 => {
          arr.push(item[item2])
        })
        return arr
      })
      //以时间戳的方式命名文件导出名字
      let filename = Date.now()

      export_json_to_excel({
        multiHeader,
        multiHeader2,
        header: Object.keys(rules),
        data: newArr,
        filename: filename,
        merges
      })
    }

导出表格的样式如下

在这里插入图片描述
这样处理之后是不是好看些哈哈


总结

以上的处理方式只是我所遇到的问题的一些处理方式,之前没有处理过这种,摸索了挺多天的,所以想记录一下,如果能帮助到有需要的人,那我也是很开心的,第一次写博客记录,不足之处欢迎指出~~~

参考博客:https://www.cnblogs.com/yeminglong/p/14760749.html

Logo

前往低代码交流专区

更多推荐