员工导出excel功能
目标: 实现将员工数据导出功能
日常业务中,我们经常遇到excel导出功能, 怎么使用呢
Excel 的导入导出都是依赖于js-xlsx来实现的。
在 js-xlsx
的基础上又封装了Export2Excel.js来方便导出数据。
使用
由于 Export2Excel
不仅依赖js-xlsx
还依赖file-saver
和script-loader
。
所以你先需要安装如下命令:
npm install xlsx file-saver -S
npm install script-loader -S -D
由于js-xlsx
体积还是很大的,导出功能也不是一个非常常用的功能,所以使用的时候建议使用懒加载。使用方法如下:
import('@/vendor/Export2Excel').then(excel => {
excel.export_json_to_excel({
header: tHeader, //表头 必填
data, //具体数据 必填
filename: 'excel-list', //非必填
autoWidth: true, //非必填
bookType: 'xlsx' //非必填
})
})
参数
参数 | 说明 | 类型 | 可选值 | 默认值 |
---|---|---|---|---|
header | 导出数据的表头 | Array | / | [] |
data | 导出的具体数据 | Array | / | [[]] |
filename | 导出文件名 | String | / | excel-list |
autoWidth | 单元格是否要自适应宽度 | Boolean | true / false | true |
bookType | 导出文件类型 | String | xlsx, csv, txt, more | xlsx |
我们最重要的一件事,就是把表头和数据进行相应的对应
因为数据中的key是英文,想要导出的表头是中文的话,需要将中文和英文做对应
const headers = {
'手机号': 'mobile',
'姓名': 'username',
'入职日期': 'timeOfEntry',
'聘用形式': 'formOfEmployment',
'转正日期': 'correctionTime',
'工号': 'workNumber',
'部门': 'departmentName'
}
其次,我们需要引入一个公共的插件 在资源中的**
excel导出
**中, 我们将其拷贝到src目录下
然后,完成导出代码
// 导出excel数据
exportData() {
// 做操作
// 表头对应关系
const headers = {
'姓名': 'username',
'手机号': 'mobile',
'入职日期': 'timeOfEntry',
'聘用形式': 'formOfEmployment',
'转正日期': 'correctionTime',
'工号': 'workNumber',
'部门': 'departmentName'
}
// 懒加载
import('@/vendor/Export2Excel').then(async excel => {
const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
const data = this.formatJson(headers, rows)
excel.export_json_to_excel({
header: Object.keys(headers),
data,
filename: '员工信息表',
autoWidth: true,
bookType: 'xlsx'
})
// 获取所有的数据
// excel.export_json_to_excel({
// header: ['姓名', '薪资'],
// data: [['张三', 12000], ['李四', 5000]],
// filename: '员工薪资表',
// autoWidth: true,
// bookType: 'csv'
// })
})
},
// 该方法负责将数组转化成二维数组
formatJson(headers, rows) {
// 首先遍历数组
// [{ username: '张三'},{},{}] => [[’张三'],[],[]]
return rows.map(item => {
return Object.keys(headers).map(key => {
if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
return formatDate(item[headers[key]]) // 返回格式化之前的时间
} else if (headers[key] === 'formOfEmployment') {
var en = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
return en ? en.value : '未知'
}
return item[headers[key]]
}) // => ["张三", "13811","2018","1", "2018", "10002"]
})
// return data
// return rows.map(item => {
// // item是对象 => 转化成只有值的数组 => 数组值的顺序依赖headers {username: '张三' }
// // Object.keys(headers) => ["姓名", "手机号",...]
// return Object.keys(headers).map(key => {
// return item[headers[key]]
// }) // / 得到 ['张三',’129‘,’dd‘,'dd']
// })
}
提交代码
**本节任务
**实现将员工数据导出功能