导入就是通过input的file属性来实现
1.安装依赖包
npm install -S xlsx
2.代码
//做一些格式转换
transExcel(results) {
const userRelations = {
'入职日期': 'timeOfEntry',
'手机号': 'mobile',
'姓名': 'username',
'转正日期': 'correctionTime',
'工号': 'workNumber',
'部门': 'departmentName',
'聘用形式': 'formOfEmployment'
}
return results.map(item => {
const obj = {}
// 将导入的文件表头汉字替换为英文
const zhKeys = Object.keys(item)
zhKeys.forEach(zhKey => {
const enKey = userRelations[zhKey]
// 如果是日期格式 那么调用封装的方法,将其转换为自己需要的格式
if (enKey === 'correctionTime' || enKey === 'timeOfEntry') {
obj[enKey] = new Date(formatExcelDate(item[zhKey]))
} else {
obj[enKey] = item[zhKey]
}
})
return obj
})
},
// 导入之后的处理
async handleSuccess({ header, results }) {
try {
// 将经过上面的函数处理后的数据保存到 arr 变量中
const arr = this.transExcel(results)
// console.log('转换之后的格式', arr)
// 调用上传的接口,将 arr 发送到后端 成功后数据会自动渲染到页面中
const res = await importEmployee(arr)
// console.log('调用上传的接口', res)
// 成功后,返回刚才的页面
this.$router.back()
// 提示信息
this.$message.success('操作成功')
} catch (err) {
// console.log(err)
this.$message.error(err.message)
}
}