Vue+iview将表格table以excel文件导出的几种方式

前言

在日常工作中,若是经常跟后台管理系统打交道的朋友想必对导出excel表格这种需求肯定很熟悉吧。不过我也问了身边的一些岗位为后端工程师的朋友,他们说在公司的话一般导出excel表格的工作一般由后端来做,前端只需要调用接口即可。我的话,由前端导出或者后端导出的两种方式我都有做过,以此想记录一下,总结一下我是如何针对不同的方式将表格数据以excel的格式导出的。同时呢,若文章中有不足的地方,也欢迎大家的指正,相互学习~

后端导出

如果你在工作中,导出excel表格这个工作主要放在后端的话,那么就会比较简单啦,前端只需要向后台发起请求,后端则会返回这个excel文件,我们只需要在前端将其下载下来即可,以下是具体的实现方式:

导出的主要逻辑:@/utils/excel文件下的exportExcel方法


/**
 * @param {function} callback
 * @param {Object} value
 * 导出数据->二进制流转成Blob
 */
export function exportExcel(data, excelName) {
  let blob = new Blob([data], { type: 'application/vnd.ms-excel' })//一定要指定这个type,具体是要看后台返回的文件是什么格式,可能有点不一样
  const $link = document.createElement('a')
  $link.href = URL.createObjectURL(blob)
  $link.download = `${excelName}.xlsx`
  $link.click()
  document.body.appendChild($link)
  document.body.removeChild($link)
  window.URL.revokeObjectURL($link.href)
}

向后台发送请求,拿到文件流,再调用上面的exportExcel方法直接在前端进行下载

import { exportExcel } from '@/utils/excel'

 // 后端导出)
    async exportYear() {
      this.exportExcelYearLoading = true
      const res = await exportListYear(this.listQuery)//exportListYear是请求api,this.listQuery是请求参数,这个实际情况根据你们的业务需求来
      exportExcel(res.data, this.excelYearName)//exportExcel是在这里做了一层封装,便于其他页面也有导出功能的复用
      setTimeout(() => {
        this.exportExcelYearLoading = false
      }, 1000)
    },

注意点:前端请求的时候接收数据的格式也需要定义的,不然无法正确接收到后台返回的正确数据格式,如以下:

// 导出排班信息
export function exportList(data) {
  return request({
    url: '/hsz/manage/gvs/workShiftManage/export',
    method: 'post',
    responseType: 'blob',//这个类型一定要定义
    data: qs.stringify(data)
  })
}

前端导出

由于项目中用的是Vue+iView,且原本iView组件的表格中有自带导出表格的功能,只不过导出的格式cvs的格式,如果需求没有规定一定是excel格式的,可以使用这个方法,毕竟特别方面,我们只需要调用即可

使用iView自带的导出csv文件

Vue+iview将表格table以excel文件导出的几种方式_第1张图片

Vue+iview将表格table以excel文件导出的几种方式_第2张图片 

 然后我们这里的需求是,可以导出用户搜索过滤后的结果,同时也是导出所有的数据而非当前页,因此这里就要给exportCsv指定data数据。具体的实现如下:

	exportDevices(type) {
      this.pageIndex = -1//目的是为了请求所有的数据
      this.pageSize = 10
      this.getDevList()//获取得到所有数据deviceList
      this.tableLoading = true
      setTimeout(() => {
        this.$refs.table.exportCsv({
          filename: 'Sorting and filtering data',
          original: false,
          // data: this.deviceList,//如果没有特殊的格式处理,则这里直接写入请求回来的表格数据
          data: this.deviceList.map(k => {
            k.deviceId = '\t' + k.deviceId//这里是对数据进行了二次处理,比如有些整型的数据过长的时候,导出的表格会显示科学计数的方式,这里是换行操作
            return k
          })
        })
      }, 1000)
      setTimeout(() => {
        this.pageIndex = 1//导出表格后恢复为第一页数据
        this.pageSize = 10
        this.getDevList()
        this.tableLoading = false
      }, 1000)
    }

注意:针对若用户有进行搜索过滤的操作时,我们只导出用户过滤之后的结果这个问题,由于我们在获取表格dataList数据的时候,请求参数必然会带有过滤条件,若用户有进行搜索记录,那避让data中的搜索参会会记录用户的搜索记录,则dataList也会跟着实时变化,那此时我们导出来的表格数据必然是搜索之后的结果。

借助Blob.js 和 Export2Excel.js实现前端导出excel文件

具体操作步骤如下

1.下载相关的依赖包

  • npm install -S file-saver //用来生成文件的web应用程序
  • npm install -S xlsx //电子表格格式的解析器
  • npm install -D script-loader //将js挂在在全局下

2.将Blob.js 和 Export2Excel.js放在assets目录下(下文会给出这两个文件的具体代码,需要的朋友可以下方自取),同个层级,比如:

Vue+iview将表格table以excel文件导出的几种方式_第3张图片

3.代码实现

    exportDevices() {
      this.pageIndex = -1
      this.pageSize = 10
      this.getDevList()
      this.tableLoading = true
      setTimeout(() => {
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/assets/js/Export2Excel') //这个地址和页面的位置相关,这个地址是
          const tHeader = [this.$t('deviceCenter.deviceId'), this.$t('deviceCenter.deviceName'), this.$t('deviceCenter.mac'), this.$t('deviceCenter.online'), this.$t('deviceCenter.productId'), this.$t('deviceCenter.productName'), this.$t('deviceCenter.secret'), this.$t('deviceCenter.syncStatus'), this.$t('deviceCenter.tenantId'), this.$t('deviceCenter.createTime'), this.$t('deviceCenter.updateTime')]//表头header
          const filterVal = ['deviceId', 'deviceName', 'mac', 'online', 'productId', 'productName', 'secret', 'syncStatus', 'tenantId', 'createTime', 'updateTime']; //与表格数据配合 可以是iview表格中的key的数组
          const data = this.formatJson(filterVal, this.dataList)
          console.log('格式化前的数据', this.dataList)
          console.log('格式化后的数据', data)
          export_json_to_excel(tHeader, data, '列表excel') //列表excel  这个是导出表单的名称
        })
      }, 500)
      setTimeout(() => {
        this.pageIndex = 1
        this.pageSize = 10
        this.getDevList()
        this.tableLoading = false
      }, 1000)
    },
    //json数据数据转换
    formatJson(filterVal, tableData) {
      return tableData.map(v => {
        return filterVal.map(j => {
          return v[j]
        })
      })
    },
	

 附件:Blob.js 和 Export2Excel.js文件

Blob.js文件:

/* 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));

Export2Excel.js文件 

说明:这里需要注意第二行代码require('script-loader!./Blob.js'); //转二进制用,在Export2Excel.js文件中有引入了Blob.js文件,因此这里的路径你要写正确哈!我这里 是将它们放在同一个目录下,因此只需要./Blob.js即可,./表示当前目录

require('script-loader!file-saver'); //保存文件用
require('script-loader!./Blob.js'); //转二进制用
require('script-loader!xlsx/dist/xlsx.core.min'); //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")
}

function formatJson(jsonData) {
}
export function export_json_to_excel(th, jsonData, defaultTitle) {

    /* original data */

    var data = jsonData;
    data.unshift(th);
    var ws_name = "SheetJS";

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


    /* 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' });
    var title = defaultTitle || '列表'
    saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), title + ".xlsx")
}

以上便是Vue+iView将数据表格导出的几种实现方式,撒花~

你可能感兴趣的:(JavaScript,Vue,iView,vue.js,view,design,前端)