參考地址:https://www.jianshu.com/p/5c131c27841c
<template>
<button @click="downloadExl(result)">導出</button>
</template>
<script>
//引入xlsx (package.json中添加依賴,這里自動引入)
import XLSX from 'xlsx';
export default {
data () {
return {
result:{},
pager:{
pageNumber:1,
pageSize:10,
pageCount:0,
recordCount:0
},
jsono:
[{ //測試數據
"id": 1,//A
"合並的列頭1": "數據11",//B
"合並的列頭2": "數據12",//C
"合並的列頭3": "數據13",//D
"合並的列頭4": "數據14",//E
}, {
"id": 2,
"合並的列頭1": "數據21",
"合並的列頭2": "數據22",
"合並的列頭3": "數據23",
"合並的列頭4": "數據24",
}],
wopts: { bookType: 'xlsx', bookSST: true, type: 'binary' }
}
},
mounted:function(){
this.flash();
},
methods: {
saveAs(obj, fileName) {//當然可以自定義簡單的下載文件實現方式
var tmpa = document.createElement("a");
tmpa.download = fileName || "下載";
tmpa.href = URL.createObjectURL(obj); //綁定a標簽
tmpa.click(); //模擬點擊實現下載
setTimeout(function () { //延時釋放
URL.revokeObjectURL(obj); //用URL.revokeObjectURL()來釋放這個object URL
}, 100);
},
downloadExl(data, type) {
var wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
//wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通過json_to_sheet轉成單頁(Sheet)數據
data = XLSX.utils.json_to_sheet(data);
// data["B1"] = { t: "s", v: "asdad" };
// data["!merges"] = [{//合並第一行數據[B1,C1,D1,E1]
// s: {//s為開始
// c: 1,//開始列
// r: 0//開始取值范圍
// },
// e: {//e結束
// c: 4,//結束列
// r: 0//結束范圍
// }
// }];
wb.Sheets['Sheet1'] = data;
this.saveAs(new Blob([this.s2ab(XLSX.write(wb, this.wopts))], { type: "application/octet-stream"}), "這里是下載的文件名" + '.' + (this.wopts.bookType == "biff2" ? "xls" : this. wopts.bookType));
},
s2ab(s) {
if (typeof ArrayBuffer !== 'undefined') {
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;
} else {
var buf = new Array(s.length);
for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
},
//這里是我自己從后台獲取的對象集合(自己用時獲取自己的數據)
flash:function(url){
if(!url){
url='waterflow/all';
}
this.$http.post(url,{
pageNumber:this.pager.pageNumber,
pageSize:this.pager.pageSize,
pageCount:this.pager.pageCount,
recordCount:this.pager.recordCount
}).then(function(response){
if(response.body.status==1){
this.result= response.body.items;
this.pager=response.body.page;
}else{
if(response.body.status==10101){
this.$Message.info("請登陸!");
this.$router.push ('/');
}
this.$Message.info(response.body.message);
}
}, function(){
});
},
}
}
</script>