最近做项目遇到Excel导入导出的问题,总结一下
1. Excel表格导入时,将中文key转为英文key
Excel表格中读入的是姓名,而后端需要的是username
[{'姓名':'小张', '手机号': '13712345678'}{.....}]
我们需要将他转换为
[ {'username':'小张','mobile': '13712345678'}, {.....} ]
把一个对象数组中的每个对象的属性名,从中文改成英文
思路:对于原数组每个对象来说
-
找出所有的中文key
-
得到对应的英文key
-
拼接一个新对象: 英文key:值
format(result, header) { const mapInfo = { '入职日期': 'timeOfEntry', '手机号': 'mobile', '姓名': 'username', '转正日期': 'correctionTime', '工号': 'workNumber', '部门': 'departmentName', '聘用形式': 'formOfEmployment' } const arr = result.map(it => { const enobj = {} header.forEach(zhkey => { const enkey = mapInfo[zhkey] if (enkey === 'timeOfEntry' || enkey === 'correctionTime') { enobj[enkey] = new Date(formatExcelDate(it[zhkey])) } else { enobj[enkey] = it[zhkey] } }) arr.push(enobj) }) return arr },
2. 导出Excel表格时,将英文key转化为中文key
formatData(list) {
const map = {
'id': '编号',
'password': '密码',
'mobile': '手机号',
'username': '姓名',
'timeOfEntry': '入职日期',
'formOfEmployment': '聘用形式',
'correctionTime': '转正日期',
'workNumber': '工号',
'departmentName': '部门',
'staffPhoto': '头像地址'
}
console.log(list)
let header = []
// header = ['id', 'mobile', 'username', .....]
// data = [ // ['65c2', '1380000002', '管理员', ....],
// ['65c3', '1380000003', '孙财', ....],
// ]
let data = []
// 开始代码
// 找到一个元素
const one = list[0]
if (!one) {
return { header, data }
}
header = Object.keys(one).map(key => {
return map[key]
})
// data把list中每一个对象转成 对应的value数组
data = list.map(obj1 => {
// 把 Obj['formOfEmployment']: 1 , 2 ---> '正式', '非正式'
const key = obj1['formOfEmployment'] // 1, 2
obj1['formOfEmployment'] = obj[key] // hireTypEnmu:{1:'正式', '2':'非正式' }
return Object.values(obj1)
})
return { header, data }
},
3. 将excel文件中的日期格式的内容转回成标准时间
// 把excel文件中的日期格式的内容转回成标准时间
// https://blog.csdn.net/qq_15054679/article/details/107712966
export function formatExcelDate(numb, format = '/') {
const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
time.setYear(time.getFullYear())
const year = time.getFullYear() + ''
const month = time.getMonth() + 1 + ''
const date = time.getDate() + ''
if (format && format.length === 1) {
return year + format + month + format + date
}
return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}