js导入excel 数据转换(属性key转英文_数值型日期转标准时间)

需要处理的是两个方向

1. excel日期的格式转换

2. key转为英文


 直接上代码吧, 大家应该看得懂

下面是统一处理1 和 2的代码

1 完整代码

// 转换excel 文件值
    transform2AxiosExcel(results) {
      // 字段中文转英文。excel中读入的是姓名,而后端需要的是username
      // 日期处理。从excel中读入的时间是一个number值,而后端需要的是标准日期。
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      const keys = Object.keys(mapInfo)
      return results.map(item => {
        return keys.reduce((obj, key) => {
          // 判断是否是非格式化日期, 用util内的函数格式化 xxxx/xx/xx
          // 再根据接口文档 需要new Date()转成标准时间 Fri Nov 05 2021 00:00:00 GMT+0800 (中国标准时间)
          if (key === '转正日期' || key === '入职日期') {
            obj[mapInfo[key]] = new Date(formatExcelDate(item[key]))
          } else {
            obj[mapInfo[key]] = item[key]
          }
          return obj
        }, {})
      })
    },

2 上面代码中excel数值型日期转换的方法

formatExcelDate方法定义在utils/index, 就是转换默认excel 数值型日期的方法, 用了csdn一位博主的方法, 里面有链接. 记得转换后默认是2023/1/1 这样的格式, 需要转换成Fri Nov 05 2021 00:00:00 GMT+0800 (中国标准时间) 套个new Date( ) 就行

下面是代码

// 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)
}

猜你喜欢

转载自blog.csdn.net/qq_59650449/article/details/128516295
今日推荐