1. First import the required dependency packages (the following are the corresponding versions I use)
npm install --save xlsx@0.17.3
npm install --save file-saver@2.0.5
2. Import in the required file (I put the file in excel.js under utils, and put the download link at the bottom, no points are required)
// 导出按钮
<el-button native-type="submit" type="primary" @click="exportExcel()">
导出
</el-button>
// 引入到文件来
import {
export_json_to_excel } from '@/utils/excel'
// 使用方法
const exportExcel = async () => {
let params = {
} // 接口请求的参数
let data = [] // 用于接受接口返回的数据
await getList(params).then((res) => {
// 调用接口
data = state.tableData = res.data.list
})
const tHeader = [
'ID',
'用户昵称',
'手机号',
]
const headersRelations = {
ID: 'id',
用户昵称: 'name',
手机号: 'mobile',
}
const resArr = formatFn(data, tHeader, headersRelations)
let dataExcel = {
header: tHeader,
data: resArr,
filename: '消息推送',
}
export_json_to_excel(dataExcel)
}
const formatFn = (list, tHeader, headersRelations) => {
// 把对象数组转换成二维数组
const oneArr = []
// 遍历对象
list.forEach((item) => {
const twoArr = []
tHeader.forEach((key) => {
const englishkey = headersRelations[key]
let value = item[englishkey]
twoArr.push(value)
})
oneArr.push(twoArr)
})
return oneArr
}
Download file address: excel.js