一文教会你把excel上传的数据转为后端要求的数据格式

176 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第21天,点击查看活动详情

excel文件如下

姓名手机号入职日期转正日期工号部门
小张138000002522021/11/52022/11/279002总裁办
小李138100005122021/11/62022/11/289006总裁办
老凡136143456702020/11/72022/11/299998总裁办

读取到浏览器的数据如下,我们发现日期变成了数值,这里我们后面会处理

后端要求数据格式:

确定需要转换的部分

1.中文属性名换为对应的英文属性名

2.日期格式转换

中文属性名换为对应的英文属性名实现

思路:

  • 1.封装一个转换函数
  • 2.设定一个对象,对象中的键值对是,中文名属性名对应英文属性值,方便后面根据中文得到对应英文
  • 3.使用数组的map方法返回一个新的数组
  • 4.遍历传入的数组,得到每一个元素的中文属性名的数组
  • 5.定义一个新的对象,给新对象的属性名为英文名,属性值为对应的中文属性名的属性值'
  • 6.返回这个新对象组成的新数组

方法一,map和forEach方法组合实现

 // excel数据转化为后端需要的数据
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(item => {
        // 先获得所有的中文属性名 数组
        const chkeys = Object.keys(item)
        // 然后新建一个对象
        const obj = {}
        // 遍历中文属性名,建立一个英文属性名的 对象
        chkeys.forEach(chkey => {
          // 给obj设定对应的中文的英文名
          const enkey = mapInfo[chkey]
          obj[enkey] = item[chkey]
        })
        // 返回obj
        return obj
      })
    },

方法一,map和reduce方法组合实现

    // excel数据转化为后端需要的数据
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(item => {
        // 先获得所有的中文属性名 数组
        const chkeys = Object.keys(item)
        return chkeys.reduce((acc, chkey) => {
          acc[mapInfo[chkey]] = item[chkey]
          return acc
        }, {})
      })
    },

返回值

日期格式转换

上面可知,excel存储日期,是把日期转化为数字存储

日期2021/11/5会转化为44505

这是因为 excel的日期是以1900-1-0开始计算的,即1900-1-1存储为数字1

因此 把excel文件中的日期格式的内容转回成标准时间代码如下

// 把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)
}
const res = formatExcelDate('2323')
console.log(res)

返回值如图

image.png