1、安装插件

  1. npm install file-saver --save
  2. npm install script-loader -D
  3. npm install xlsx --save

在src目录,utils文件夹下新建 Blob.js 和 Export2Excel.jsimage.png

  1. /*global self, unescape */
  2. /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
  3. plusplus: true */
  4. (function(view) {
  5. "use strict";
  6. view.URL = view.URL || view.webkitURL;
  7. if (view.Blob && view.URL) {
  8. try {
  9. new Blob();
  10. return;
  11. } catch (e) {}
  12. }
  13. // Internally we use a BlobBuilder implementation to base Blob off of
  14. // in order to support older browsers that only have BlobBuilder
  15. var BlobBuilder =
  16. view.BlobBuilder ||
  17. view.WebKitBlobBuilder ||
  18. view.MozBlobBuilder ||
  19. (function(view) {
  20. var get_class = function(object) {
  21. return Object.prototype.toString
  22. .call(object)
  23. .match(/^\[object\s(.*)\]$/)[1];
  24. },
  25. FakeBlobBuilder = function BlobBuilder() {
  26. this.data = [];
  27. },
  28. FakeBlob = function Blob(data, type, encoding) {
  29. this.data = data;
  30. this.size = data.length;
  31. this.type = type;
  32. this.encoding = encoding;
  33. },
  34. FBB_proto = FakeBlobBuilder.prototype,
  35. FB_proto = FakeBlob.prototype,
  36. FileReaderSync = view.FileReaderSync,
  37. FileException = function(type) {
  38. this.code = this[(this.name = type)];
  39. },
  40. file_ex_codes = (
  41. "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR " +
  42. "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
  43. ).split(" "),
  44. file_ex_code = file_ex_codes.length,
  45. real_URL = view.URL || view.webkitURL || view,
  46. real_create_object_URL = real_URL.createObjectURL,
  47. real_revoke_object_URL = real_URL.revokeObjectURL,
  48. URL = real_URL,
  49. btoa = view.btoa,
  50. atob = view.atob,
  51. ArrayBuffer = view.ArrayBuffer,
  52. Uint8Array = view.Uint8Array;
  53. FakeBlob.fake = FB_proto.fake = true;
  54. while (file_ex_code--) {
  55. FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
  56. }
  57. if (!real_URL.createObjectURL) {
  58. URL = view.URL = {};
  59. }
  60. URL.createObjectURL = function(blob) {
  61. var type = blob.type,
  62. data_URI_header;
  63. if (type === null) {
  64. type = "application/octet-stream";
  65. }
  66. if (blob instanceof FakeBlob) {
  67. data_URI_header = "data:" + type;
  68. if (blob.encoding === "base64") {
  69. return data_URI_header + ";base64," + blob.data;
  70. } else if (blob.encoding === "URI") {
  71. return data_URI_header + "," + decodeURIComponent(blob.data);
  72. }
  73. if (btoa) {
  74. return data_URI_header + ";base64," + btoa(blob.data);
  75. } else {
  76. return data_URI_header + "," + encodeURIComponent(blob.data);
  77. }
  78. } else if (real_create_object_URL) {
  79. return real_create_object_URL.call(real_URL, blob);
  80. }
  81. };
  82. URL.revokeObjectURL = function(object_URL) {
  83. if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
  84. real_revoke_object_URL.call(real_URL, object_URL);
  85. }
  86. };
  87. FBB_proto.append = function(data /*, endings*/) {
  88. var bb = this.data;
  89. // decode data to a binary string
  90. if (
  91. Uint8Array &&
  92. (data instanceof ArrayBuffer || data instanceof Uint8Array)
  93. ) {
  94. var str = "",
  95. buf = new Uint8Array(data),
  96. i = 0,
  97. buf_len = buf.length;
  98. for (; i < buf_len; i++) {
  99. str += String.fromCharCode(buf[i]);
  100. }
  101. bb.push(str);
  102. } else if (get_class(data) === "Blob" || get_class(data) === "File") {
  103. if (FileReaderSync) {
  104. var fr = new FileReaderSync();
  105. bb.push(fr.readAsBinaryString(data));
  106. } else {
  107. // async FileReader won't work as BlobBuilder is sync
  108. throw new FileException("NOT_READABLE_ERR");
  109. }
  110. } else if (data instanceof FakeBlob) {
  111. if (data.encoding === "base64" && atob) {
  112. bb.push(atob(data.data));
  113. } else if (data.encoding === "URI") {
  114. bb.push(decodeURIComponent(data.data));
  115. } else if (data.encoding === "raw") {
  116. bb.push(data.data);
  117. }
  118. } else {
  119. if (typeof data !== "string") {
  120. data += ""; // convert unsupported types to strings
  121. }
  122. // decode UTF-16 to binary string
  123. bb.push(unescape(encodeURIComponent(data)));
  124. }
  125. };
  126. FBB_proto.getBlob = function(type) {
  127. if (!arguments.length) {
  128. type = null;
  129. }
  130. return new FakeBlob(this.data.join(""), type, "raw");
  131. };
  132. FBB_proto.toString = function() {
  133. return "[object BlobBuilder]";
  134. };
  135. FB_proto.slice = function(start, end, type) {
  136. var args = arguments.length;
  137. if (args < 3) {
  138. type = null;
  139. }
  140. return new FakeBlob(
  141. this.data.slice(start, args > 1 ? end : this.data.length),
  142. type,
  143. this.encoding
  144. );
  145. };
  146. FB_proto.toString = function() {
  147. return "[object Blob]";
  148. };
  149. FB_proto.close = function() {
  150. this.size = this.data.length = 0;
  151. };
  152. return FakeBlobBuilder;
  153. })(view);
  154. view.Blob = function Blob(blobParts, options) {
  155. var type = options ? options.type || "" : "";
  156. var builder = new BlobBuilder();
  157. if (blobParts) {
  158. for (var i = 0, len = blobParts.length; i < len; i++) {
  159. builder.append(blobParts[i]);
  160. }
  161. }
  162. return builder.getBlob(type);
  163. };
  164. })(
  165. (typeof self !== "undefined" && self) ||
  166. (typeof window !== "undefined" && window) ||
  167. this.content ||
  168. this
  169. );
  1. //Export2Excel.js
  2. require("script-loader!file-saver");
  3. // require("script-loader!./Blob.js"); //转二进制用 引入项目中的blob的实际路径
  4. require('./Blob');//转二进制用
  5. require("script-loader!xlsx/dist/xlsx.core.min");
  6. function generateArray(table) {
  7. var out = [];
  8. var rows = table.querySelectorAll("tr");
  9. var ranges = [];
  10. for (var R = 0; R < rows.length; ++R) {
  11. var outRow = [];
  12. var row = rows[R];
  13. var columns = row.querySelectorAll("td");
  14. for (var C = 0; C < columns.length; ++C) {
  15. var cell = columns[C];
  16. var colspan = cell.getAttribute("colspan");
  17. var rowspan = cell.getAttribute("rowspan");
  18. var cellValue = cell.innerText;
  19. if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
  20. //Skip ranges
  21. ranges.forEach(function(range) {
  22. if (
  23. R >= range.s.r &&
  24. R <= range.e.r &&
  25. outRow.length >= range.s.c &&
  26. outRow.length <= range.e.c
  27. ) {
  28. for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
  29. }
  30. });
  31. //Handle Row Span
  32. if (rowspan || colspan) {
  33. rowspan = rowspan || 1;
  34. colspan = colspan || 1;
  35. ranges.push({
  36. s: {
  37. r: R,
  38. c: outRow.length
  39. },
  40. e: {
  41. r: R + rowspan - 1,
  42. c: outRow.length + colspan - 1
  43. }
  44. });
  45. }
  46. //Handle Value
  47. outRow.push(cellValue !== "" ? cellValue : null);
  48. //Handle Colspan
  49. if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
  50. }
  51. out.push(outRow);
  52. }
  53. return [out, ranges];
  54. }
  55. function datenum(v, date1904) {
  56. if (date1904) v += 1462;
  57. var epoch = Date.parse(v);
  58. return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
  59. }
  60. function sheet_from_array_of_arrays(data, opts) {
  61. var ws = {};
  62. var range = {
  63. s: {
  64. c: 10000000,
  65. r: 10000000
  66. },
  67. e: {
  68. c: 0,
  69. r: 0
  70. }
  71. };
  72. for (var R = 0; R != data.length; ++R) {
  73. for (var C = 0; C != data[R].length; ++C) {
  74. if (range.s.r > R) range.s.r = R;
  75. if (range.s.c > C) range.s.c = C;
  76. if (range.e.r < R) range.e.r = R;
  77. if (range.e.c < C) range.e.c = C;
  78. var cell = {
  79. v: data[R][C]
  80. };
  81. if (cell.v == null) continue;
  82. var cell_ref = XLSX.utils.encode_cell({
  83. c: C,
  84. r: R
  85. });
  86. if (typeof cell.v === "number") cell.t = "n";
  87. else if (typeof cell.v === "boolean") cell.t = "b";
  88. else if (cell.v instanceof Date) {
  89. cell.t = "n";
  90. cell.z = XLSX.SSF._table[14];
  91. cell.v = datenum(cell.v);
  92. } else cell.t = "s";
  93. ws[cell_ref] = cell;
  94. }
  95. }
  96. if (range.s.c < 10000000) ws["!ref"] = XLSX.utils.encode_range(range);
  97. return ws;
  98. }
  99. function Workbook() {
  100. if (!(this instanceof Workbook)) return new Workbook();
  101. this.SheetNames = [];
  102. this.Sheets = {};
  103. }
  104. function s2ab(s) {
  105. var buf = new ArrayBuffer(s.length);
  106. var view = new Uint8Array(buf);
  107. for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
  108. return buf;
  109. }
  110. export function export_table_to_excel(id) {
  111. var theTable = document.getElementById(id);
  112. console.log("a");
  113. var oo = generateArray(theTable);
  114. var ranges = oo[1];
  115. /* original data */
  116. var data = oo[0];
  117. var ws_name = "SheetJS";
  118. console.log(data);
  119. var wb = new Workbook(),
  120. ws = sheet_from_array_of_arrays(data);
  121. /* add ranges to worksheet */
  122. // ws['!cols'] = ['apple', 'banan'];
  123. ws["!merges"] = ranges;
  124. /* add worksheet to workbook */
  125. wb.SheetNames.push(ws_name);
  126. wb.Sheets[ws_name] = ws;
  127. var wbout = XLSX.write(wb, {
  128. bookType: "xlsx",
  129. bookSST: false,
  130. type: "binary"
  131. });
  132. saveAs(
  133. new Blob([s2ab(wbout)], {
  134. type: "application/octet-stream"
  135. }),
  136. "test.xlsx"
  137. );
  138. }
  139. function formatJson(jsonData) {
  140. console.log(jsonData);
  141. }
  142. export function export_json_to_excel(th, jsonData, defaultTitle) {
  143. /* original data */
  144. var data = jsonData;
  145. data.unshift(th);
  146. var ws_name = "SheetJS";
  147. var wb = new Workbook(),
  148. ws = sheet_from_array_of_arrays(data);
  149. /* add worksheet to workbook */
  150. wb.SheetNames.push(ws_name);
  151. wb.Sheets[ws_name] = ws;
  152. var wbout = XLSX.write(wb, {
  153. bookType: "xlsx",
  154. bookSST: false,
  155. type: "binary"
  156. });
  157. var title = defaultTitle || "列表";
  158. saveAs(
  159. new Blob([s2ab(wbout)], {
  160. type: "application/octet-stream"
  161. }),
  162. title + ".xlsx"
  163. );
  164. }

使用

(1) 如果项目中有很多地方用到导出数据成表格,则在 main.js中引入 Blob.js 和 Export2Excel.js

  1. //在main.js中
  2. // 注意引入 Blob.js 和 Export2Excel.js 的路径
  3. import Blob from '@/utils/Blob.js'
  4. import Export2Excel from '@/utils/Export2Excel.js'

(2) 如果项目中只有一个地方用到,则可以在要使用到的页面里引入:

  1. //在main.js中
  2. // 注意引入 Blob.js 和 Export2Excel.js 的路径
  3. import Blob from '@/utils/Blob.js'
  4. import Export2Excel from '@/utils/Export2Excel.js'
  5. // 导入excel插件,挂载到全局
  6. import XLSX from 'xlsx';
  7. Vue.prototype.XLSX = XLSX;

(3) 以下以在项目中全局使用为例(已在main.js中引入):

  1. <template>
  2. <div>
  3. <el-button size="small" type="primary" @click="exportExcel" icon="el-icon-download">导出</el-button>
  4. </div>
  5. </template>
  6. <script>
  7. import {
  8. addmaterial,
  9. updatematerial,
  10. getmaterials_by_cid_mid,
  11. get_materials_page,
  12. getall_citys,
  13. getall_mtypes,
  14. getall_stypes,
  15. updatematerial_main,
  16. } from "../../api/api";
  17. export default {
  18. data() {
  19. return {
  20. selectList: [], // 选中的数据
  21. }
  22. },
  23. methods: {
  24. //选中某条数据时
  25. handleSelectionChange(row) {
  26. this.selectList = row; // 将选中的数据给selectList
  27. },
  28. //定义导出Excel表格事件
  29. exportExcel() {
  30. if (this.selectList.length === 0) {
  31. this.$message({
  32. message: "请至少选择一条需要导出的数据",
  33. type: "warning",
  34. });
  35. return;
  36. }
  37. this.$msgbox
  38. .confirm("该操作将导出选中的数据,是否继续", "提示", {
  39. confirmButtonText: "确定",
  40. cancelButtonText: "取消",
  41. type: "warning",
  42. })
  43. .then(() => {
  44. //导出
  45. require.ensure([], () => {
  46. const { export_json_to_excel } = require("@/utils/Export2Excel"); //注意这个Export2Excel路径
  47. const tableHeader = [
  48. "地市",
  49. "教材名称",
  50. "教材类型",
  51. "创建时间",
  52. "描述",
  53. "教材地址",
  54. ]; // 设置Excel表格的表头内容
  55. const header = [];
  56. const filterVal = [
  57. "province",
  58. "mname",
  59. "lname",
  60. "createdate",
  61. "memo",
  62. "path",
  63. ]; // 跟表格表头对应的绑定的prop 属性值
  64. // let list = this.filterTableData(
  65. // JSON.parse(JSON.stringify(this.selectList))
  66. // ); // this.selectList为选中的要导出的数据,用filterTableData方法先处理一下数据格式(要进行深度拷贝,以免过滤的时候,影响页面上展示的数据),再存到list
  67. let data = this.formatJson(filterVal, list);
  68. export_json_to_excel(tableHeader,header, data, "教材管理"); //最后一个是导出表格的名字
  69. });
  70. })
  71. .catch(() => {});
  72. },
  73. formatJson(filterVal, Data) {
  74. return Data.map(v => filterVal.map(j => v[j]))
  75. },
  76. //导出数据前对数据处理,变为想要的格式。
  77. filterTableData(data) {
  78. data.forEach((item) => {
  79. item.country ? (item.province =item.province +"-" +item.city +"-" +item.area +"-" +
  80. item.country)
  81. : (item.province = item.province + "-" + item.city + "-" + item.area);
  82. item.isdel ? (item.isdel = "已开启") : "已关闭";
  83. });
  84. return data;
  85. },
  86. }
  87. </script>

(3)以上步骤就可以把table 表格数据导出为excel 了。