持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第25天,点击查看活动详情
背景
在表格(element-table)中查询到了我们需要的数据,希望用他们生成excel文件,保存在本地。
思路
1.前端主导
取回数据,生成excel文件
2.后端主导
前端调用接口
实现方案
1. 将vue-element-admin中的src/vendor/export2Excel复制到本项目中,直接使用
2.在项目中安装依赖
npm install file-saver script-loader xlsx --save
3.给导出按钮添加点击事件
import('@/vendor/Export2Excel').then(excel => {
// excel表示导入的模块对象
console.log(excel)
excel.export_json_to_excel({
header: ['姓名', '工资'], // 表头 必填
data: [
['刘备', 100],
['关羽', 500]
], // 具体数据 必填
filename: 'excel-list', // 文件名称
autoWidth: true, // 宽度是否自适应
bookType: 'xlsx' // 生成的文件类型
})
})
以上代码表示:
- 当我们正式点击
导出
按钮之后,才去加载vendor文件夹中的Export2Excel模块 - import方法执行完毕返回的是一个promise对象,在then方法中我们可以拿到使用的模块对象
- 重点关注data的配置部分,它需要一个二维数组
Excel导出参数说明
参数 | 说明 | 类型 | 可选值 | 默认值 |
---|---|---|---|---|
header | 导出数据的表头 | Array | / | [] |
data | 导出的具体数据 | Array | / | [[]] |
filename | 导出文件名 | String | / | excel-list |
autoWidth | 单元格是否要自适应宽度 | Boolean | true / false | true |
bookType | 导出文件类型 | String | xlsx, csv, txt, more | xlsx |
4.真实数据导出
// 3.8导出excel
hExportExcel() {
import('@/vendor/Export2Excel').then(async excel => {
// excel表示导入的模块对象
console.log(excel)
// (1)发请求
const { data: res } = await getEmployees({ page: this.page, size: this.size })
// (2)调用数据转化函数,得到header和data
const { header, data } = this.formatData(res.rows)
// (3)导出excel
excel.export_json_to_excel({
header, // 表头 必填
data, // 具体数据 必填
filename: '员工列表', // 文件名称
autoWidth: true, // 宽度是否自适应
bookType: 'xlsx' // 生成的文件类型
})
})
},
// 3.9表格数据转为excel数据
formatData(list) {
// 标题中英文映射对象
const map = {
'id': '编号',
'password': '密码',
'mobile': '手机号',
'username': '姓名',
'timeOfEntry': '入职日期',
'formOfEmployment': '聘用形式',
'correctionTime': '转正日期',
'workNumber': '工号',
'departmentName': '部门',
'staffPhoto': '头像地址'
}
// 获得表头
let header = Object.keys(list[0])
console.log(header)
// 得到data
const data = list.map(item => {
// 聘用形式改为1对应正式,2对应非正式
// 雇佣形式
const formMap = {
'1': '正式',
'2': '非正式'
}
item['formOfEmployment'] = formMap[item['formOfEmployment']]
return header.map(key => item[key])
})
console.log(data)
// 中文头部
header = header.map(key => map[key])
return { header, data }
}