體驗更優排版請移步原文:http://blog.kwin.wang/programming/vue-table-export-excel-and-print.html
頁面中顯示的table表格,經常會要求實現導出Excel的需求,項目中剛好遇到,實現起來也比較簡單,記錄一下。
1.這里主要需要兩個依賴:xlsx、
file-saver
:
npm install xlsx --save
npm install file-saver --save
2.組件中引入
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
3.組件中導出Excel的方法
//導出Excel
exportToExcel () { let et = XLSX.utils.table_to_book(document.getElementById('table-content')); //此處傳入table的DOM節點
let etout = XLSX.write(et, { bookType: 'xlsx', bookSST: true, type: 'array' }); try { FileSaver.saveAs(new Blob([etout], { type: 'application/octet-stream' }), 'trade-publish.xlsx'); //trade-publish.xlsx 為導出的文件名
} catch (e) { console.log(e, etout) ; } return etout; }
4.導出按鈕執行exportToExcel方法即可
<el-button @click="exportToExcel">導出</el-button>
5.打印頁面部分內容的實現方法
//打印頁面內容
printContent(){ let wpt = document.getElementById('table-content'); let newContent = wpt.innerHTML; let oldContent = document.body.innerHTML; document.body.innerHTML = newContent; window.print(); //打印方法
window.localtion.reload(); document.body.innerHTML = oldContent; }
方法的實現很容易理解,打印的體驗也比較好,妙!
End…