引言:
最近使用vue在做一個后臺系統,技術棧 vue + iView ,在頁面中生成表格后, iView可以實現表格的導出,不過只能導出csv格式的,并不適合項目需求。
如果想要導出Excel
在src目錄下創建一個文件(vendor)進入 Blob.js 和 Export2Excel.js npm install -S file-saver 用來生成文件的web應用程序 npm install -S xlsx 電子表格格式的解析器 npm install -D script-loader 將js掛在在全局下表結構
渲染頁面中的表結構是由 columns 列 和 tableData 行,來渲染的 columns 為表頭數據 tableData 為表實體內容
columns1: [ { title: '序號', key: 'serNum' }, { title: '選擇', key: 'choose', align: 'center', render: (h, params) => { if (params.row.status !== '1' && params.row.status !== '2') { return h('div', [ h('checkbox', { props: { type: 'selection' }, on: { 'input': (val) => { console.log(val) } } }) ]) } else { return h('span', { style: { color: '#587dde', cursor: 'pointer' }, on: { click: () => { // this.$router.push({name: '', query: { id: params.row.id }}) } } }, '查看訂單') } } }, ... ],tableData 就不寫了,具體數據結構查看iViewAPI
在build 目錄下 webpack.base.conf.js 配置 我們要加載時的路徑
alias: { 'src': path.resolve(__dirname, '../src'), }在當前頁面中引入依賴
require('script-loader!file-saver') // 轉二進制用 require('script-loader!src/vendor/Blob') // xlsx核心 require('script-loader!xlsx/dist/xlsx.core.min')當我們要導出表格執行 @click 事件調用 handleDownload 函數
handleDownload() { this.downloadLoading = true require.ensure([], () => { const {export_json_to_excel} = require('src/vendor/Export2Excel') const tHeader = Util.cutValue(this.columns1, 'title') const filterVal = Util.cutValue(this.columns1, 'key') const list = this.tableData1 const data = this.formatJson(filterVal, list) export_json_to_excel(tHeader, data, '列表excel') this.downloadLoading = false }) }, formatJson(filterVal, jsonData) { return jsonData.map(v => filterVal.map(j => v[j])) }Util.cutValue 是公共方法,目的是為了將,tHeader 和filterVal 的值轉成數組從而生成表格
### Util module// 截取value值utils.cutValue = function (target, name) { let arr = [] for (let i = 0; i < target.length; i++) { arr.push(target[i][name]) } return arr}Export2Excel.js/Blob.js 的代碼
下面再看下vue中excel表格的導入和導出
注意:vue中要實現表格的導入與導出,首先要install兩個依賴,
npm install -S file-saver xlsx 和
新聞熱點
疑難解答
圖片精選