美文网首页
excel2object.js

excel2object.js

作者: _Charles | 来源:发表于2018-10-22 19:23 被阅读0次

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
}

相关文章

  • excel2object.js

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

网友评论

      本文标题:excel2object.js

      本文链接:https://www.haomeiwen.com/subject/bdfnzftx.html