目标
数据格式转换:将 excel 解析好的数据经过处理后,转成可以传给接口调用的数据
实现
-
字段中文转英文。excel中读入的是
姓名
,而后端需要的是username
-
日期处理。从excel中读入的时间是一个 number 值,而后端需要的是标准日期
数据
-
Excel原数据
-
目标数据
代码
// 导入格式化时间的方法
import { formatExcelDate } from '@/utils'
transExcel(results) {
// 定义一份需要枚举的数据,实现中文和英文的对应关系
const userRelations = {
'入职日期': 'timeOfEntry',
'手机号': 'mobile',
'姓名': 'username',
'转正日期': 'correctionTime',
'工号': 'workNumber',
'部门': 'departmentName',
'聘用形式': 'formOfEmployment'
}
// map 方法最终返回数组
return results.map(item => {
// 声明一个变量,这个变量的 key 是英文的
const obj = {}
// 将每一项中文的 key 组成一个数组
// 1. 取出这个对象所有的属性名: ['姓名', '手机号', '']
// 2. 遍历这个数组,通过 中文名去 userRelations 找对应英文名, 保存值
const contentKeys = Object.keys(item)
contentKeys.forEach(key => {
// 利用枚举数据,取到中文 key 对应的 英文
const transKeys = userRelations[key]
// 将 入职日期、转正日期 格式化后传给obj对象
if (transKeys === 'correctionTime' || transKeys === 'timeOfEntry') {
// 将时间转化成标准的时间戳
obj[transKeys] = new Date(formatExcelDate(item[key]))
} else {
// 将 obj 的其他属性直接传给obj对象
// item[key] {}['姓名']
obj[transKeys] = item[key]
}
})
return obj
})
}
// 格式化 Excel 中的时间
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)
}