加载中...

Vue 导出Excel表格,并实现合并单元格方法

 安装依赖:

"file-saver" 是一个 JavaScript 库,用于在浏览器中保存文件。它提供了一种简单的方式,允许你通过 JavaScript 在客户端创建和下载文件,而无需服务器的参与。使用 file-saver,你可以将生成的数据(例如从后端获取的数据或处理后的数据)保存为文件,让用户可以下载和保存到本地计算机。

cnpm install file-saver --save

 "xlsx" 是用于 Microsoft Excel 文件的文件格式。它代表 "XML Spreadsheet",常用于存储和处理电子表格数据。在 Web 开发中,你可以使用各种 JavaScript 库来处理 xlsx 文件,提供读取、写入和操作 Excel 文件的功能。

cnpm install xlsx --save

"script-loader" 是一个用于动态加载 JavaScript 脚本的工具。它提供了一种在运行时加载外部 JavaScript 文件的方法,而无需在 HTML 中显式添加 <script> 标签。这对于按需加载特定的 JavaScript 文件或根据条件加载不同的脚本文件很有用。使用 script-loader,你可以在需要时异步加载和执行 JavaScript 代码,以优化页面加载性能和资源利用率。

cnpm install script-loader --save-dev

 下载Export2Excel.js文件 在src下创建目录vassets/Export2Excel.js

以下是下载好的Export2Excel.js文件:

  1. /* eslint-disable */
  2. import { saveAs } from ''file-saver''
  3. import * as XLSX from ''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({
  29. s: {
  30. r: R,
  31. c: outRow.length
  32. },
  33. e: {
  34. r: R + rowspan - 1,
  35. c: outRow.length + colspan - 1
  36. }
  37. });
  38. };
  39. //Handle Value
  40. outRow.push(cellValue !== "" ? cellValue : null);
  41. //Handle Colspan
  42. if (colspan)
  43. for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
  44. }
  45. out.push(outRow);
  46. }
  47. return [out, ranges];
  48. };
  49. function datenum(v, date1904) {
  50. if (date1904) v += 1462;
  51. var epoch = Date.parse(v);
  52. return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  53. }
  54. function sheet_from_array_of_arrays(data, opts) {
  55. var ws = {};
  56. var range = {
  57. s: {
  58. c: 10000000,
  59. r: 10000000
  60. },
  61. e: {
  62. c: 0,
  63. r: 0
  64. }
  65. };
  66. for (var R = 0; R != data.length; ++R) {
  67. for (var C = 0; C != data[R].length; ++C) {
  68. if (range.s.r > R) range.s.r = R;
  69. if (range.s.c > C) range.s.c = C;
  70. if (range.e.r < R) range.e.r = R;
  71. if (range.e.c < C) range.e.c = C;
  72. var cell = {
  73. v: data[R][C]
  74. };
  75. if (cell.v == null) continue;
  76. var cell_ref = XLSX.utils.encode_cell({
  77. c: C,
  78. r: R
  79. });
  80. if (typeof cell.v === ''number'') cell.t = ''n'';
  81. else if (typeof cell.v === ''boolean'') cell.t = ''b'';
  82. else if (cell.v instanceof Date) {
  83. cell.t = ''n'';
  84. cell.z = XLSX.SSF._table[14];
  85. cell.v = datenum(cell.v);
  86. } else cell.t = ''s'';
  87. ws[cell_ref] = cell;
  88. }
  89. }
  90. if (range.s.c < 10000000) ws[''!ref''] = XLSX.utils.encode_range(range);
  91. return ws;
  92. }
  93. function Workbook() {
  94. if (!(this instanceof Workbook)) return new Workbook();
  95. this.SheetNames = [];
  96. this.Sheets = {};
  97. }
  98. function s2ab(s) {
  99. var buf = new ArrayBuffer(s.length);
  100. var view = new Uint8Array(buf);
  101. for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  102. return buf;
  103. }
  104. export function export_table_to_excel(id) {
  105. var theTable = document.getElementById(id);
  106. var oo = generateArray(theTable);
  107. var ranges = oo[1];
  108. /* original data */
  109. var data = oo[0];
  110. var ws_name = "SheetJS";
  111. var wb = new Workbook(),
  112. ws = sheet_from_array_of_arrays(data);
  113. /* add ranges to worksheet */
  114. // ws[''!cols''] = [''apple'', ''banan''];
  115. ws[''!merges''] = ranges;
  116. /* add worksheet to workbook */
  117. wb.SheetNames.push(ws_name);
  118. wb.Sheets[ws_name] = ws;
  119. var wbout = XLSX.write(wb, {
  120. bookType: ''xlsx'',
  121. bookSST: false,
  122. type: ''binary''
  123. });
  124. saveAs(new Blob([s2ab(wbout)], {
  125. type: "application/octet-stream"
  126. }), "test.xlsx")
  127. }
  128. export function export_json_to_excel({
  129. multiHeader = [],
  130. header,
  131. data,
  132. filename,
  133. merges = [],
  134. autoWidth = true,
  135. bookType = ''xlsx''
  136. } = {}) {
  137. /* original data */
  138. filename = filename || ''excel-list''
  139. data = [...data]
  140. data.unshift(header);
  141. for (let i = multiHeader.length - 1; i > -1; i--) {
  142. data.unshift(multiHeader[i])
  143. }
  144. var ws_name = "SheetJS";
  145. var wb = new Workbook(),
  146. ws = sheet_from_array_of_arrays(data);
  147. if (merges.length > 0) {
  148. if (!ws[''!merges'']) ws[''!merges''] = [];
  149. merges.forEach(item => {
  150. ws[''!merges''].push(XLSX.utils.decode_range(item))
  151. })
  152. }
  153. /* add worksheet to workbook */
  154. wb.SheetNames.push(ws_name);
  155. wb.Sheets[ws_name] = ws;
  156. var wbout = XLSX.write(wb, {
  157. bookType: bookType,
  158. bookSST: false,
  159. type: ''binary''
  160. });
  161. saveAs(new Blob([s2ab(wbout)], {
  162. type: "application/octet-stream"
  163. }), `${filename}.${bookType}`);
  164. }

在组件中使用 

  1. //导出方法
  2. exportExcel () {
  3. import(''@/assets/Export2Excel'').then(excel => {
  4. const multiHeader = [[''标题'', '''','''']] // 标题
  5. const header = [''姓名'', ''年龄'',''手机号''] // 表头
  6. const filterVal = [''username'', ''age'',''mobile''] // 数据属性
  7. const list = this.tableData //请求来的数据
  8. const merges = [''A1:B1''] //需要合并的单元格
  9. const data = list.map(item => filterVal.map(j => item[j])) // 转换二维数组
  10. const filename = ''复杂员工列表''
  11. excel.export_json_to_excel({
  12. multiHeader, // 标题--非必要
  13. header, // 表头
  14. data, // 具体数据--二维数组
  15. merges, // 合并--非必要
  16. filename // 下载文件名
  17. })
  18. })
  19. }

tableData数据结构:

  1. tableData: [{
  2. correctionTime: ''2018-11-30'',
  3. mobile: ''13800000001'',
  4. timeOfEntry: ''2025-11-01'',
  5. username: ''张三'',
  6. age: ''21''
  7. },
  8. {
  9. correctionTime: ''2018-11-30'',
  10. mobile: ''13800000002'',
  11. timeOfEntry: ''2025-11-01'',
  12. username: ''李四'',
  13. age: ''23''
  14. }]