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


    前言

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

    后端导出

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

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

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

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

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

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

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

    前端导出

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

    使用iView自带的导出csv文件

     

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

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

    注意:针对若用户有进行搜索过滤的操作时,我们只导出用户过滤之后的结果这个问题,由于我们在获取表格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目录下(下文会给出这两个文件的具体代码,需要的朋友可以下方自取),同个层级,比如:

    3.代码实现

    1. exportDevices() {
    2. this.pageIndex = -1
    3. this.pageSize = 10
    4. this.getDevList()
    5. this.tableLoading = true
    6. setTimeout(() => {
    7. require.ensure([], () => {
    8. const { export_json_to_excel } = require('@/assets/js/Export2Excel') //这个地址和页面的位置相关,这个地址是
    9. 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
    10. const filterVal = ['deviceId', 'deviceName', 'mac', 'online', 'productId', 'productName', 'secret', 'syncStatus', 'tenantId', 'createTime', 'updateTime']; //与表格数据配合 可以是iview表格中的key的数组
    11. const data = this.formatJson(filterVal, this.dataList)
    12. console.log('格式化前的数据', this.dataList)
    13. console.log('格式化后的数据', data)
    14. export_json_to_excel(tHeader, data, '列表excel') //列表excel 这个是导出表单的名称
    15. })
    16. }, 500)
    17. setTimeout(() => {
    18. this.pageIndex = 1
    19. this.pageSize = 10
    20. this.getDevList()
    21. this.tableLoading = false
    22. }, 1000)
    23. },
    24. //json数据数据转换
    25. formatJson(filterVal, tableData) {
    26. return tableData.map(v => {
    27. return filterVal.map(j => {
    28. return v[j]
    29. })
    30. })
    31. },

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

    Blob.js文件:

    1. /* Blob.js
    2. * A Blob implementation.
    3. * 2014-05-27
    4. *
    5. * By Eli Grey, http://eligrey.com
    6. * By Devin Samarin, https://github.com/eboyjr
    7. * License: X11/MIT
    8. * See LICENSE.md
    9. */
    10. /*global self, unescape */
    11. /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
    12. plusplus: true */
    13. /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
    14. (function (view) {
    15. "use strict";
    16. view.URL = view.URL || view.webkitURL;
    17. if (view.Blob && view.URL) {
    18. try {
    19. new Blob;
    20. return;
    21. } catch (e) {}
    22. }
    23. // Internally we use a BlobBuilder implementation to base Blob off of
    24. // in order to support older browsers that only have BlobBuilder
    25. var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
    26. var
    27. get_class = function(object) {
    28. return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
    29. }
    30. , FakeBlobBuilder = function BlobBuilder() {
    31. this.data = [];
    32. }
    33. , FakeBlob = function Blob(data, type, encoding) {
    34. this.data = data;
    35. this.size = data.length;
    36. this.type = type;
    37. this.encoding = encoding;
    38. }
    39. , FBB_proto = FakeBlobBuilder.prototype
    40. , FB_proto = FakeBlob.prototype
    41. , FileReaderSync = view.FileReaderSync
    42. , FileException = function(type) {
    43. this.code = this[this.name = type];
    44. }
    45. , file_ex_codes = (
    46. "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
    47. + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
    48. ).split(" ")
    49. , file_ex_code = file_ex_codes.length
    50. , real_URL = view.URL || view.webkitURL || view
    51. , real_create_object_URL = real_URL.createObjectURL
    52. , real_revoke_object_URL = real_URL.revokeObjectURL
    53. , URL = real_URL
    54. , btoa = view.btoa
    55. , atob = view.atob
    56. , ArrayBuffer = view.ArrayBuffer
    57. , Uint8Array = view.Uint8Array
    58. ;
    59. FakeBlob.fake = FB_proto.fake = true;
    60. while (file_ex_code--) {
    61. FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
    62. }
    63. if (!real_URL.createObjectURL) {
    64. URL = view.URL = {};
    65. }
    66. URL.createObjectURL = function(blob) {
    67. var
    68. type = blob.type
    69. , data_URI_header
    70. ;
    71. if (type === null) {
    72. type = "application/octet-stream";
    73. }
    74. if (blob instanceof FakeBlob) {
    75. data_URI_header = "data:" + type;
    76. if (blob.encoding === "base64") {
    77. return data_URI_header + ";base64," + blob.data;
    78. } else if (blob.encoding === "URI") {
    79. return data_URI_header + "," + decodeURIComponent(blob.data);
    80. } if (btoa) {
    81. return data_URI_header + ";base64," + btoa(blob.data);
    82. } else {
    83. return data_URI_header + "," + encodeURIComponent(blob.data);
    84. }
    85. } else if (real_create_object_URL) {
    86. return real_create_object_URL.call(real_URL, blob);
    87. }
    88. };
    89. URL.revokeObjectURL = function(object_URL) {
    90. if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
    91. real_revoke_object_URL.call(real_URL, object_URL);
    92. }
    93. };
    94. FBB_proto.append = function(data/*, endings*/) {
    95. var bb = this.data;
    96. // decode data to a binary string
    97. if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
    98. var
    99. str = ""
    100. , buf = new Uint8Array(data)
    101. , i = 0
    102. , buf_len = buf.length
    103. ;
    104. for (; i < buf_len; i++) {
    105. str += String.fromCharCode(buf[i]);
    106. }
    107. bb.push(str);
    108. } else if (get_class(data) === "Blob" || get_class(data) === "File") {
    109. if (FileReaderSync) {
    110. var fr = new FileReaderSync;
    111. bb.push(fr.readAsBinaryString(data));
    112. } else {
    113. // async FileReader won't work as BlobBuilder is sync
    114. throw new FileException("NOT_READABLE_ERR");
    115. }
    116. } else if (data instanceof FakeBlob) {
    117. if (data.encoding === "base64" && atob) {
    118. bb.push(atob(data.data));
    119. } else if (data.encoding === "URI") {
    120. bb.push(decodeURIComponent(data.data));
    121. } else if (data.encoding === "raw") {
    122. bb.push(data.data);
    123. }
    124. } else {
    125. if (typeof data !== "string") {
    126. data += ""; // convert unsupported types to strings
    127. }
    128. // decode UTF-16 to binary string
    129. bb.push(unescape(encodeURIComponent(data)));
    130. }
    131. };
    132. FBB_proto.getBlob = function(type) {
    133. if (!arguments.length) {
    134. type = null;
    135. }
    136. return new FakeBlob(this.data.join(""), type, "raw");
    137. };
    138. FBB_proto.toString = function() {
    139. return "[object BlobBuilder]";
    140. };
    141. FB_proto.slice = function(start, end, type) {
    142. var args = arguments.length;
    143. if (args < 3) {
    144. type = null;
    145. }
    146. return new FakeBlob(
    147. this.data.slice(start, args > 1 ? end : this.data.length)
    148. , type
    149. , this.encoding
    150. );
    151. };
    152. FB_proto.toString = function() {
    153. return "[object Blob]";
    154. };
    155. FB_proto.close = function() {
    156. this.size = this.data.length = 0;
    157. };
    158. return FakeBlobBuilder;
    159. }(view));
    160. view.Blob = function Blob(blobParts, options) {
    161. var type = options ? (options.type || "") : "";
    162. var builder = new BlobBuilder();
    163. if (blobParts) {
    164. for (var i = 0, len = blobParts.length; i < len; i++) {
    165. builder.append(blobParts[i]);
    166. }
    167. }
    168. return builder.getBlob(type);
    169. };
    170. }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));

    Export2Excel.js文件 

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

    1. require('script-loader!file-saver'); //保存文件用
    2. require('script-loader!./Blob.js'); //转二进制用
    3. require('script-loader!xlsx/dist/xlsx.core.min'); //xlsx核心
    4. function generateArray(table) {
    5. var out = [];
    6. var rows = table.querySelectorAll('tr');
    7. var ranges = [];
    8. for (var R = 0; R < rows.length; ++R) {
    9. var outRow = [];
    10. var row = rows[R];
    11. var columns = row.querySelectorAll('td');
    12. for (var C = 0; C < columns.length; ++C) {
    13. var cell = columns[C];
    14. var colspan = cell.getAttribute('colspan');
    15. var rowspan = cell.getAttribute('rowspan');
    16. var cellValue = cell.innerText;
    17. if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
    18. //Skip ranges
    19. ranges.forEach(function (range) {
    20. if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
    21. for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
    22. }
    23. });
    24. //Handle Row Span
    25. if (rowspan || colspan) {
    26. rowspan = rowspan || 1;
    27. colspan = colspan || 1;
    28. ranges.push({ s: { r: R, c: outRow.length }, e: { r: R + rowspan - 1, c: outRow.length + colspan - 1 } });
    29. }
    30. ;
    31. //Handle Value
    32. outRow.push(cellValue !== "" ? cellValue : null);
    33. //Handle Colspan
    34. if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
    35. }
    36. out.push(outRow);
    37. }
    38. return [out, ranges];
    39. };
    40. function datenum(v, date1904) {
    41. if (date1904) v += 1462;
    42. var epoch = Date.parse(v);
    43. return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
    44. }
    45. function sheet_from_array_of_arrays(data, opts) {
    46. var ws = {};
    47. var range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } };
    48. for (var R = 0; R != data.length; ++R) {
    49. for (var C = 0; C != data[R].length; ++C) {
    50. if (range.s.r > R) range.s.r = R;
    51. if (range.s.c > C) range.s.c = C;
    52. if (range.e.r < R) range.e.r = R;
    53. if (range.e.c < C) range.e.c = C;
    54. var cell = { v: data[R][C] };
    55. if (cell.v == null) continue;
    56. var cell_ref = XLSX.utils.encode_cell({ c: C, r: R });
    57. if (typeof cell.v === 'number') cell.t = 'n';
    58. else if (typeof cell.v === 'boolean') cell.t = 'b';
    59. else if (cell.v instanceof Date) {
    60. cell.t = 'n';
    61. cell.z = XLSX.SSF._table[14];
    62. cell.v = datenum(cell.v);
    63. }
    64. else cell.t = 's';
    65. ws[cell_ref] = cell;
    66. }
    67. }
    68. if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    69. return ws;
    70. }
    71. function Workbook() {
    72. if (!(this instanceof Workbook)) return new Workbook();
    73. this.SheetNames = [];
    74. this.Sheets = {};
    75. }
    76. function s2ab(s) {
    77. var buf = new ArrayBuffer(s.length);
    78. var view = new Uint8Array(buf);
    79. for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    80. return buf;
    81. }
    82. export function export_table_to_excel(id) {
    83. var theTable = document.getElementById(id);
    84. var oo = generateArray(theTable);
    85. var ranges = oo[1];
    86. /* original data */
    87. var data = oo[0];
    88. var ws_name = "SheetJS";
    89. var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
    90. /* add ranges to worksheet */
    91. // ws['!cols'] = ['apple', 'banan'];
    92. ws['!merges'] = ranges;
    93. /* add worksheet to workbook */
    94. wb.SheetNames.push(ws_name);
    95. wb.Sheets[ws_name] = ws;
    96. var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
    97. saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), "test.xlsx")
    98. }
    99. function formatJson(jsonData) {
    100. }
    101. export function export_json_to_excel(th, jsonData, defaultTitle) {
    102. /* original data */
    103. var data = jsonData;
    104. data.unshift(th);
    105. var ws_name = "SheetJS";
    106. var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
    107. /* add worksheet to workbook */
    108. wb.SheetNames.push(ws_name);
    109. wb.Sheets[ws_name] = ws;
    110. var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: false, type: 'binary' });
    111. var title = defaultTitle || '列表'
    112. saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), title + ".xlsx")
    113. }

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

  • 相关阅读:
    嵌入式系统开发笔记91:认识ARM微控制器架构
    String字符串性能优化的几种方案
    openssl客户端编程:一个不起眼的函数导致的SSL会话失败问题
    bash和sh的区别
    IP 协议的相关特性(部分)
    159_模型_Power BI 地理分析之形状地图
    如何用python写 翻译腔?天哪~这实在是太有趣了~
    锥坡 锥坡 锥坡
    长事务管理不再难:Saga模式全面解析
    为什么免费证书的有效期为90天
  • 原文地址:https://blog.csdn.net/weixin_46872121/article/details/128053498