Vue中导出excel表格文件xlsx

1.安装依赖

npm install -S file-saver
npm install -S xlsx
npm install -D script-loader

2.新建lib文件夹,并创建Blob.js和Export2Excel.js文件

 

3.在Blob.js中输入以下代码

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

4.在Export2Excel.js中输入以下代码

  1 /* eslint-disable */
  2 require('script-loader!file-saver');
  3 require('script-loader!./Blob');  //引用当前目录下的Blob.js模块
  4 require('script-loader!xlsx/dist/xlsx.core.min');
  5 //由于这几个文件不支持import引入,所以我们需要`script-loader`来将他们挂载到全局环境下
  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 
 21             //Skip ranges
 22             ranges.forEach(function (range) {
 23                 if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
 24                     for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
 25                 }
 26             });
 27 
 28             //Handle Row Span
 29             if (rowspan || colspan) {
 30                 rowspan = rowspan || 1;
 31                 colspan = colspan || 1;
 32                 ranges.push({s: {r: R, c: outRow.length}, e: {r: R + rowspan - 1, c: outRow.length + colspan - 1}});
 33             }
 34             ;
 35 
 36             //Handle Value
 37             outRow.push(cellValue !== "" ? cellValue : null);
 38 
 39             //Handle Colspan
 40             if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
 41         }
 42         out.push(outRow);
 43     }
 44     return [out, ranges];
 45 };
 46 
 47 function datenum(v, date1904) {
 48     if (date1904) v += 1462;
 49     var epoch = Date.parse(v);
 50     return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
 51 }
 52 
 53 function sheet_from_array_of_arrays(data, opts) {
 54     var ws = {};
 55     var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
 56     for (var R = 0; R != data.length; ++R) {
 57         for (var C = 0; C != data[R].length; ++C) {
 58             if (range.s.r > R) range.s.r = R;
 59             if (range.s.c > C) range.s.c = C;
 60             if (range.e.r < R) range.e.r = R;
 61             if (range.e.c < C) range.e.c = C;
 62             var cell = {v: data[R][C]};
 63             if (cell.v == null) continue;
 64             var cell_ref = XLSX.utils.encode_cell({c: C, r: R});
 65 
 66             if (typeof cell.v === 'number') cell.t = 'n';
 67             else if (typeof cell.v === 'boolean') cell.t = 'b';
 68             else if (cell.v instanceof Date) {
 69                 cell.t = 'n';
 70                 cell.z = XLSX.SSF._table[14];
 71                 cell.v = datenum(cell.v);
 72             }
 73             else cell.t = 's';
 74 
 75             ws[cell_ref] = cell;
 76         }
 77     }
 78     if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
 79     return ws;
 80 }
 81 
 82 function Workbook() {
 83     if (!(this instanceof Workbook)) return new Workbook();
 84     this.SheetNames = [];
 85     this.Sheets = {};
 86 }
 87 
 88 function s2ab(s) {
 89     var buf = new ArrayBuffer(s.length);
 90     var view = new Uint8Array(buf);
 91     for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
 92     return buf;
 93 }
 94 
 95 export function export_table_to_excel(id) {
 96     var theTable = document.getElementById(id);
 97     console.log('a')
 98     var oo = generateArray(theTable);
 99     var ranges = oo[1];
100 
101     /* original data */
102     var data = oo[0];
103     var ws_name = "SheetJS";
104     console.log(data);
105 
106     var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
107 
108     /* add ranges to worksheet */
109     // ws['!cols'] = ['apple', 'banan'];
110     ws['!merges'] = ranges;
111 
112     /* add worksheet to workbook */
113     wb.SheetNames.push(ws_name);
114     wb.Sheets[ws_name] = ws;
115 
116     var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
117 
118     saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), "test.xlsx")
119 }
120 
121 function formatJson(jsonData) {
122     console.log(jsonData)
123 }
124 export function export_json_to_excel(th, jsonData, defaultTitle) {
125 
126     /* original data */
127 
128     var data = jsonData;
129     data.unshift(th);
130     var ws_name = "SheetJS";
131 
132     var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
133 
134     /* add worksheet to workbook */
135     wb.SheetNames.push(ws_name);
136     wb.Sheets[ws_name] = ws;
137 
138     var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
139     var title = defaultTitle || '列表'
140     saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
141 }
Export2Excel.js

5.在相应vue页面的methods中添加以下方法

export2Excel(){
      require.ensure([],()=>{
        const {export_json_to_excel } = require('../lib/Export2Excel.js')  //刚刚新建Export2Excel.js文件的路径
        const tHeader = ['组名','创建时间']   //自定义列名
        const filterVal = ['title','create_date']   //对应自怼
        const list = this.tableData   //table数据
        const data = this.formatJson(filterVal,list);
        export_json_to_excel(tHeader,data,'列表excel');  //导出文件名称
      })
    },
    formatJson(filterVal,jsonData){
      console.info(jsonData)
      return jsonData.map(v => filterVal.map(j=> v[j]))
    },
    port(){
      this.export2Excel()
    },

6.绑定按钮事件

<el-button size="small" type="success" @click="port">导出为excel表格</el-button>

猜你喜欢

转载自www.cnblogs.com/liudaya/p/12982237.html