格式化Excel文件中的数据

目标

数据格式转换:将 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)
}

格式化时间:formatExcelDate()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值