vue導(dǎo)出excel表格功能

第一步安裝依賴包?

? ???cnpm install??file-saver

? ???cnpm install?xlsx

? ? ?cnpm install?script-loader

第二步在項目中assets下創(chuàng)建一個新的文件夾js用于存放Blob和Export2Excel兩個js文件

第三步在你那個組件中使用

tHeader:標題

filterVal:字段名

tableData:前端請求的數(shù)據(jù)

exportToExcel() {

//excel數(shù)據(jù)導(dǎo)出

? require.ensure([], () => {

const {

export_json_to_excel

? ? } = require('../../assets/js/Export2Excel');

const tHeader = ['序號','姓名','用戶名','性別','郵箱'];

const filterVal = ['userId','name','username','sex','email'];

const list =this.users;

const data =this.formatJson(filterVal,list);

export_json_to_excel(tHeader,data,'用戶列表');

})

},

formatJson(filterVal, jsonData) {

return jsonData.map(v => filterVal.map(j => v[j]))

},

export2Excel.js

/* eslint-disable */

require('script-loader!file-saver');

// require('script-loader!src/vendor/Blob');

require('script-loader!../../assets/js/Blob');

require('script-loader!xlsx/dist/xlsx.core.min');

function generateArray(table) {

var out = [];

var rows = table.querySelectorAll('tr');

var ranges = [];

for (var R =0;R

var outRow = [];

var row =rows[R];

var columns =row.querySelectorAll('td');

for (var C =0;C

var cell =columns[C];

var colspan =cell.getAttribute('colspan');

var rowspan =cell.getAttribute('rowspan');

var cellValue =cell.innerText;

if (cellValue !=="" &&cellValue == +cellValue)cellValue = +cellValue;

//Skip ranges

? ? ? ranges.forEach(function (range) {

if (R >= range.s.r &&R <= range.e.r &&outRow.length >= range.s.c &&outRow.length <= range.e.c) {

for (var i =0;i <= range.e.c - range.s.c; ++i)outRow.push(null);

}

});

//Handle Row Span

? ? ? if (rowspan ||colspan) {

rowspan =rowspan ||1;

colspan =colspan ||1;

ranges.push({s: {r:R,c:outRow.length},e: {r:R +rowspan -1,c:outRow.length +colspan -1}});

}

;

//Handle Value

? ? ? outRow.push(cellValue !=="" ?cellValue :null);

//Handle Colspan

? ? ? if (colspan)for (var k =0;k

}

out.push(outRow);

}

return [out,ranges];

};

function datenum(v, date1904) {

if (date1904) v +=1462;

var epoch =Date.parse(v);

return (epoch -new Date(Date.UTC(1899,11,30))) / (24 *60 *60 *1000);

}

function sheet_from_array_of_arrays(data, opts) {

var ws = {};

var range = {s: {c:10000000,r:10000000},e: {c:0,r:0}};

for (var R =0;R != data.length; ++R) {

for (var C =0;C != data[R].length; ++C) {

if (range.s.r >R)range.s.r =R;

if (range.s.c >C)range.s.c =C;

if (range.e.r

if (range.e.c

var cell = {v: data[R][C]};

if (cell.v ==null)continue;

var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

if (typeof cell.v ==='number')cell.t ='n';

else if (typeof cell.v ==='boolean')cell.t ='b';

else if (cell.v instanceof Date) {

cell.t ='n';

cell.z = XLSX.SSF._table[14];

cell.v =datenum(cell.v);

}

else cell.t ='s';

ws[cell_ref] =cell;

}

}

if (range.s.c <10000000)ws['!ref'] = XLSX.utils.encode_range(range);

return ws;

}

function Workbook() {

if (!(this instanceof Workbook))return new Workbook();

this.SheetNames = [];

this.Sheets = {};

}

function s2ab(s) {

var buf =new ArrayBuffer(s.length);

var view =new Uint8Array(buf);

for (var i =0;i != s.length; ++i)view[i] = s.charCodeAt(i) &0xFF;

return buf;

}

export function export_table_to_excel(id) {

var theTable =document.getElementById(id);

console.log('a')

var oo =generateArray(theTable);

var ranges =oo[1];

/* original data */

? var data =oo[0];

var ws_name ="SheetJS";

console.log(data);

var wb =new Workbook(),ws =sheet_from_array_of_arrays(data);

/* add ranges to worksheet */

// ws['!cols'] = ['apple', 'banan'];

? ws['!merges'] =ranges;

/* add worksheet to workbook */

? wb.SheetNames.push(ws_name);

wb.Sheets[ws_name] =ws;

var wbout = XLSX.write(wb, {bookType:'xlsx',bookSST:false,type:'binary'});

saveAs(new Blob([s2ab(wbout)], {type:"application/octet-stream"}),"test.xlsx")

}

function formatJson(jsonData) {

console.log(jsonData)

}

export function export_json_to_excel(th, jsonData, defaultTitle) {

/* original data */

? var data = jsonData;

data.unshift(th);

var ws_name ="SheetJS";

var wb =new Workbook(),ws =sheet_from_array_of_arrays(data);

/* add worksheet to workbook */

? wb.SheetNames.push(ws_name);

wb.Sheets[ws_name] =ws;

var wbout = XLSX.write(wb, {bookType:'xlsx',bookSST:false,type:'binary'});

var title = defaultTitle ||'列表'

? saveAs(new Blob([s2ab(wbout)], {type:"application/octet-stream"}),title +".xlsx")

}

Blob.js

/* eslint-disable */

/* Blob.js*/

/*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

,origin =/^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/

? ? ;

FakeBlob.fake =FB_proto.fake =true;

while (file_ex_code--) {

FileException.prototype[file_ex_codes[file_ex_code]] =file_ex_code +1;

}

// Polyfill URL

? ? if (!real_URL.createObjectURL) {

URL = view.URL =function (uri) {

var

? ? ? ? ? uri_info =document.createElementNS("http://www.w3.org/1999/xhtml","a")

,uri_origin

? ? ? ? ;

uri_info.href = uri;

if (!("origin" in uri_info)) {

if (uri_info.protocol.toLowerCase() ==="data:") {

uri_info.origin =null;

}else {

uri_origin = uri.match(origin);

uri_info.origin =uri_origin &&uri_origin[1];

}

}

return uri_info;

};

}

URL.createObjectURL =function (blob) {

var

? ? ? ? type = blob.type

? ? ? ? ,data_URI_header

? ? ? ;

if (type ===null) {

type ="application/octet-stream";

}

if (blobinstanceof 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 && (datainstanceof ArrayBuffer || datainstanceof Uint8Array)) {

var

? ? ? ? ? str =""

? ? ? ? ? ,buf =new Uint8Array(data)

,i =0

? ? ? ? ? ,buf_len =buf.length

? ? ? ? ;

for (;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 (datainstanceof 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 =0;

delete this.data;

};

return FakeBlobBuilder;

}(view));

view.Blob =function (blobParts, options) {

var type = options ? (options.type ||"") :"";

var builder =new BlobBuilder();

if (blobParts) {

for (var i =0,len = blobParts.length;i

if (Uint8Array && blobParts[i]instanceof Uint8Array) {

builder.append(blobParts[i].buffer);

}

else {

builder.append(blobParts[i]);

}

}

}

var blob =builder.getBlob(type);

if (!blob.slice &&blob.webkitSlice) {

blob.slice =blob.webkitSlice;

}

return blob;

};

var getPrototypeOf =Object.getPrototypeOf ||function (object) {

return object.__proto__;

};

view.Blob.prototype =getPrototypeOf(new view.Blob());

}(

typeof self !=="undefined" &&self

? ||typeof window !=="undefined" &&window

? ||this

));

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末掂器,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌妹孙,老刑警劉巖担租,帶你破解...
    沈念sama閱讀 211,817評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異事秀,居然都是意外死亡灾梦,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,329評論 3 385
  • 文/潘曉璐 我一進店門槐雾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來夭委,“玉大人,你說我怎么就攤上這事蚜退∪蜓ィ” “怎么了?”我有些...
    開封第一講書人閱讀 157,354評論 0 348
  • 文/不壞的土叔 我叫張陵钻注,是天一觀的道長蚂且。 經(jīng)常有香客問我,道長幅恋,這世上最難降的妖魔是什么杏死? 我笑而不...
    開封第一講書人閱讀 56,498評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮捆交,結(jié)果婚禮上淑翼,老公的妹妹穿的比我還像新娘。我一直安慰自己品追,他們只是感情好玄括,可當我...
    茶點故事閱讀 65,600評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著肉瓦,像睡著了一般遭京。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上泞莉,一...
    開封第一講書人閱讀 49,829評論 1 290
  • 那天哪雕,我揣著相機與錄音,去河邊找鬼鲫趁。 笑死斯嚎,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的挨厚。 我是一名探鬼主播堡僻,決...
    沈念sama閱讀 38,979評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼疫剃!你這毒婦竟也來了苦始?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,722評論 0 266
  • 序言:老撾萬榮一對情侶失蹤慌申,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蹄溉,經(jīng)...
    沈念sama閱讀 44,189評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡咨油,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,519評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了柒爵。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片役电。...
    茶點故事閱讀 38,654評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖棉胀,靈堂內(nèi)的尸體忽然破棺而出法瑟,到底是詐尸還是另有隱情,我是刑警寧澤唁奢,帶...
    沈念sama閱讀 34,329評論 4 330
  • 正文 年R本政府宣布霎挟,位于F島的核電站,受9級特大地震影響麻掸,放射性物質(zhì)發(fā)生泄漏酥夭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,940評論 3 313
  • 文/蒙蒙 一脊奋、第九天 我趴在偏房一處隱蔽的房頂上張望熬北。 院中可真熱鬧,春花似錦诚隙、人聲如沸讶隐。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,762評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽巫延。三九已至,卻和暖如春籽孙,著一層夾襖步出監(jiān)牢的瞬間烈评,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,993評論 1 266
  • 我被黑心中介騙來泰國打工犯建, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留讲冠,地道東北人。 一個月前我還...
    沈念sama閱讀 46,382評論 2 360
  • 正文 我出身青樓适瓦,卻偏偏與公主長得像竿开,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子玻熙,可洞房花燭夜當晚...
    茶點故事閱讀 43,543評論 2 349

推薦閱讀更多精彩內(nèi)容