vue 导出excel
1、安装三个依赖包
npm install -S file-saver
npm install -S xlsx
npm install -D script-loader
2、在项目中创建一个文件夹(比如vendor,一般是在src目录下创建)
把Blob.js和 Export2Excel.js这两个文件夹放到新建的文件夹内,如图:
Blob.js:
/* eslint-disable */ /* 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:
1 /* eslint-disable */ 2 require('script-loader!file-saver'); 3 require('script-loader!vendor/Blob'); 4 require('script-loader!xlsx/dist/xlsx.core.min'); 5 function generateArray(table) { 6 var out = []; 7 var rows = table.querySelectorAll('tr'); 8 var ranges = []; 9 for (var R = 0; R < rows.length; ++R) { 10 var outRow = []; 11 var row = rows[R]; 12 var columns = row.querySelectorAll('td'); 13 for (var C = 0; C < columns.length; ++C) { 14 var cell = columns[C]; 15 var colspan = cell.getAttribute('colspan'); 16 var rowspan = cell.getAttribute('rowspan'); 17 var cellValue = cell.innerText; 18 if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue; 19 20 //Skip ranges 21 ranges.forEach(function (range) { 22 if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) { 23 for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null); 24 } 25 }); 26 27 //Handle Row Span 28 if (rowspan || colspan) { 29 rowspan = rowspan || 1; 30 colspan = colspan || 1; 31 ranges.push({s: {r: R, c: outRow.length}, e: {r: R + rowspan - 1, c: outRow.length + colspan - 1}}); 32 } 33 ; 34 35 //Handle Value 36 outRow.push(cellValue !== "" ? cellValue : null); 37 38 //Handle Colspan 39 if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null); 40 } 41 out.push(outRow); 42 } 43 return [out, ranges]; 44 }; 45 46 function datenum(v, date1904) { 47 if (date1904) v += 1462; 48 var epoch = Date.parse(v); 49 return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000); 50 } 51 52 function sheet_from_array_of_arrays(data, opts) { 53 var ws = {}; 54 var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}}; 55 for (var R = 0; R != data.length; ++R) { 56 for (var C = 0; C != data[R].length; ++C) { 57 if (range.s.r > R) range.s.r = R; 58 if (range.s.c > C) range.s.c = C; 59 if (range.e.r < R) range.e.r = R; 60 if (range.e.c < C) range.e.c = C; 61 var cell = {v: data[R][C]}; 62 if (cell.v == null) continue; 63 var cell_ref = XLSX.utils.encode_cell({c: C, r: R}); 64 65 if (typeof cell.v === 'number') cell.t = 'n'; 66 else if (typeof cell.v === 'boolean') cell.t = 'b'; 67 else if (cell.v instanceof Date) { 68 cell.t = 'n'; 69 cell.z = XLSX.SSF._table[14]; 70 cell.v = datenum(cell.v); 71 } 72 else cell.t = 's'; 73 74 ws[cell_ref] = cell; 75 } 76 } 77 if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range); 78 return ws; 79 } 80 81 function Workbook() { 82 if (!(this instanceof Workbook)) return new Workbook(); 83 this.SheetNames = []; 84 this.Sheets = {}; 85 } 86 87 function s2ab(s) { 88 var buf = new ArrayBuffer(s.length); 89 var view = new Uint8Array(buf); 90 for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; 91 return buf; 92 } 93 94 export function export_table_to_excel(id) { 95 var theTable = document.getElementById(id); 96 console.log('a') 97 var oo = generateArray(theTable); 98 var ranges = oo[1]; 99 100 /* original data */ 101 var data = oo[0]; 102 var ws_name = "SheetJS"; 103 console.log(data); 104 105 var wb = new Workbook(), ws = sheet_from_array_of_arrays(data); 106 107 /* add ranges to worksheet */ 108 // ws['!cols'] = ['apple', 'banan']; 109 ws['!merges'] = ranges; 110 111 /* add worksheet to workbook */ 112 wb.SheetNames.push(ws_name); 113 wb.Sheets[ws_name] = ws; 114 115 var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'}); 116 117 saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), "test.xlsx") 118 } 119 120 function formatJson(jsonData) { 121 console.log(jsonData) 122 } 123 export function export_json_to_excel(th, jsonData, defaultTitle) { 124 125 /* original data */ 126 127 var data = jsonData; 128 data.unshift(th); 129 var ws_name = "SheetJS"; 130 131 var wb = new Workbook(), ws = sheet_from_array_of_arrays(data); 132 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 }
3、在页面中使用
1 <template> 2 <f7-page :name="$route.route.name" :class="$route.route.name" pull-to-refresh> 3 <navbar :title="$route.route.title"></navbar> 4 <button style='margin-bottom:20px;' type="primary" icon="document" @click="handleDownload" >导出excel</button> 5 <table data="tableData" style="width: 100%"> 6 <tr> 7 <td prop="id" label="名称" width="180"></td> 8 <td prop="name" label="姓名" width="180"> 9 </td> 10 </tr> 11 </table> 12 </f7-page> 13 </template>
1 export default { 2 data(){ 3 return{ 4 table:[{ 5 id:1, 6 name:'测试1' 7 },{ 8 id:2, 9 name:'测试2' 10 },{ 11 id:3, 12 name:'测试3' 13 }] 14 } 15 }, 16 methods:{ 17 handleDownload() { 18 this.downloadLoading = true 19 require.ensure([], () => { 20 const { export_json_to_excel } = require('../../vendor/Export2Excel') 21 const tHeader = ['ID', '姓名'] 22 const filterVal = ['id', 'name'] 23 const list = this.table 24 const data = this.formatJson(filterVal, list) 25 export_json_to_excel(tHeader, data, '列表excel') 26 this.downloadLoading = false 27 }) 28 }, 29 formatJson(filterVal, jsonData) { 30 return jsonData.map(v => filterVal.map(j => v[j])) 31 } 32 } 33 }
4.在main.js(全局js文件)中加入如下代码:
在webpack.base.conf.js中加入
出现下面的错误:
首先按照提示运行该语句,如果还是不行,则需要查看上面的路径配置。然后就解决了