vue下载excel
插件代码
/**
* tH Array -- excel表头
* fV Array -- 过滤数据的key
* list Array -- 表格渲染的数据
* fileName -- 导出excel的名称
* formatJsonFun function -- 过滤数据的方法
*/
import Vue from 'vue'
export function exportExcel(tH, fV, list, formatJsonFun, fileName = 'excel-list') {
const loading = Vue.prototype.$loading({
lock: true,
text: '导出时间较长,请耐心等待^.^',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.5)'
})
return new Promise((resolve, reject) => {
import('@/vendor/Export2Excel').then(excel => {
const tHeader = tH
const filterVal = fV
let data = []
if (formatJsonFun && typeof (formatJsonFun) === 'function') {
data = formatJsonFun(filterVal, list)
} else {
data = formatJson(filterVal, list)
}
excel.export_json_to_excel({
header: tHeader,
data,
filename: fileName,
autoWidth: true,
bookType: 'xlsx'
})
loading.close()
resolve()
})
})
}
function formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => {
return v[j]
}))
}
调用
- vue 结构
<el-table :data="tableData">
<el-table-column
prop="index"
label="索引"
width="180">
</el-table-column>
<el-table-column
prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column
prop="number"
label="数量">
</el-table-column>
<el-table-column
prop="status"
label="状态">
</el-table-column>
</el-table>
<el-button type="primary" @click="exportExcelFile">导出</el-button>
- 逻辑
// 引入
import { exportExcel } from './exportEcxel'
var vm = new Vue({
el: "#app",
data: function () {
return {
tableData: [
{index: 1,date: "2021-03-12T02:46:35.000+0000",number: 10, status: 1},
{index: 2,date: "2021-03-12T02:46:35.000+0000",number: 20, status: 2},
{index: 3,date: "2021-03-12T02:46:35.000+0000",number: 30, status: 3},
{index: 4,date: "2021-03-12T02:46:35.000+0000",number: 40, status: 4},
]
}
},
methods: {
exportExcelFile() {
this.$confirm('确定要导出数据', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
const tHeader = ['索引', '日期', '数量', '状态']
const filterVal = []
exportExcel(tHeader, filterVal, this.multipleSelection, this.formatJson, '列表').then(() => {})
}).catch(() => {
console.log('取消')
})
},
// 导出的数据格式化
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => {
if (j === 'date') {
if (v[j]) {
return this.formatterDate(v[j])
} else {
return ''
}
} else if (j === 'status') {
return this.filterStatus(v[j])
}
return v[j]
}))
},
formatterDate(time) {
const date = time
if (!date) return ''
const d = new Date(date)
let mon = d.getMonth() + 1
mon = mon < 10 ? '0' + mon : mon
let day = d.getDate()
day = day < 10 ? '0' + day : day
let h = d.getHours()
h = h < 10 ? '0' + h : h
let min = d.getMinutes()
min = min < 10 ? '0' + min : min
let s = d.getSeconds()
s = s < 10 ? '0' + s : s
const times = d.getFullYear() + '-' + mon + '-' + day + ' ' + h + ':' + min + ':' + s
return times
},
filterStatus(status) {
const statusObj = {
'1': '未开售',
'2': '已上架',
'3': '已结束',
'4': '已下架'
}
return statusObj[status]
}
}
})