vue.js-json資料匯出excel(組件)
by cactus77kiki
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<div id="vapp">
<h3>json資料匯出excel檔案(單一sheet)</h3>
<ele-export-excel :buttontext="textofbutton" :filename="exportname" :exportdata="outputdata" :headdata="headdata"></ele-export-excel>
</div>
JavaScript
/*2021/7/6 adjust:
新增: 自訂xlsx標題+不將所有欄位輸出
注意: 若未將xlsx.full.min升版到(0.17.0)、FileSaver升版到(2.0.5)原先json資料的property成會出現在檔案內第一列中
*/
Vue.component('ele-export-excel',{
props:{
buttontext:{type:String}, //button text
filename:{type:String}, //xlsx file name
sheetname:{type:String}, //xlsx sheet name
exportdata:{type:Array}, //json data
headdata:{type:Array}, //xlsx column head data
},
data:function(){
return {
btntext: this.buttontext == "" ? " 匯出 Excel 檔案" : " " + this.buttontext,
filenme: this.filename == "" ? "Sample.xlsx" : this.filename +".xlsx",
sheetnme: this.sheetname == "" ? "Sheet1" : this.sheetname,
headsetting: this.headdata == null ? null : this.headdata
}
},
template:
`
<div class="form-inline" style="margin:3px;">
<button class="btn btn-primary btn-sm" v-on:click="exporting">
<i class="fa fa-download" aria-hidden="true"></i>{{btntext}}
</button>
</div>
`,
methods: {
exporting: function(){
if(this.beforexport()){
return this.export_json_to_excel();
}
},
export_json_to_excel: function(){
if(typeof XLSX == 'undefined') XLSX = require('xlsx');
var wb = XLSX.utils.book_new(); /* add to workbook */
//var ws = XLSX.utils.json_to_sheet(this.exportdata); //origin
//add column head setting --s--
var ws;
//console.log(this.headsetting);
if (this.headsetting){
ws = XLSX.utils.json_to_sheet(this.exportdata, this.headsetting);}
else{
ws = XLSX.utils.json_to_sheet(this.exportdata);
}
//add column head setting --e--
XLSX.utils.book_append_sheet(wb, ws, this.sheetnme);
var wbout = XLSX.write(wb, {bookType:'xlsx', type:'binary'});
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), this.filenme);
},
beforexport: function(){
var source = this.exportdata;
if(source){
if(source.length ==...