excel2object.js

excel 文件转 object, 其中beforeUpload方法是作为一个验证, 只有返回ture才会触发onSuccess

import XLSX from 'xlsx'

export default function({event, beforeUpload, onSuccess}) {
  const files = event.target.files
  const rawFile = files[0] // only use files[0]
  if (!rawFile) return
  upload(rawFile, beforeUpload, onSuccess)
}

function upload(rawFile, beforeUpload, onSuccess) {
  if (!beforeUpload) {
    readerData(rawFile, onSuccess)
    return
  }
  const before = beforeUpload(rawFile)
  if (before) {
    readerData(rawFile, onSuccess)
  }
}

function readerData(rawFile, onSuccess) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = e => {
      const data = e.target.result
      const fixedData = fixData(data)
      const workbook = XLSX.read(btoa(fixedData), { type: 'base64' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const header = getHeaderRow(worksheet)
      const results = XLSX.utils.sheet_to_json(worksheet)
      onSuccess({header, results})
      resolve()
    }
    reader.readAsArrayBuffer(rawFile)
  })
}

function fixData(data) {
  let o = ''
  let l = 0
  const w = 10240
  for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
  o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
  return o
}

function getHeaderRow(sheet) {
  const headers = []
  const range = XLSX.utils.decode_range(sheet['!ref'])
  let C
  const R = range.s.r
  /* start in the first row */
  for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
    const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
    /* find the cell in the first row */
    let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
    if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
    headers.push(hdr)
  }
  return headers
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,429评论 0 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,886评论 18 139
  • 英西峰林徒步,小喵在黄花小镇上遇到了一位超级“拽酷”的猫先生。 这位猫大人本来在专心打盹儿,对我的”搭讪“视而不见...
    魔旅行阅读 273评论 0 0
  • 今天,陈姓的小组长来我家了,让签土地确权的字。 这次来我家,他直奔主题,拿出一堆纸,让我在有我先生名字的那格,指定...
    金之华阅读 693评论 2 1