引言:vue
最近使用vue在作一個後臺系統,技術棧 vue + iView
,在頁面中生成表格後, iView能夠實現表格的導出,不過只能導出csv格式的,並不適合項目需求。webpack
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 就不寫了,具體數據結構查看iViewAPIgit
在build 目錄下webpack.base.conf.js
配置 咱們要加載時的路徑github
alias: {
'src': path.resolve(__dirname, '../src'),
}
複製代碼
在當前頁面中引入依賴web
require('script-loader!file-saver')
// 轉二進制用
require('script-loader!src/vendor/Blob')
// xlsx核心
require('script-loader!xlsx/dist/xlsx.core.min')
複製代碼
當咱們要導出表格執行@click
事件調用handleDownload
函數npm
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 的值轉成數組從而生成表格json
### 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
}
複製代碼