XLSX json转文本流 & json转文件

封装一个公共 xlsx.js

import { read, utils, writeFile } from 'xlsx'
// 文本流转json 
// 入参:文本流 回调 入参{}
export const readJsonFromFile = (file, callBackFn, opt) => {
  const reader = new FileReader()
  reader.readAsArrayBuffer(file)
  reader.onload = function (e) {
    const workbook = read(e.target.result)
    console.info('excel读取结果:', workbook)
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    // 读取header
    const data = utils.sheet_to_json(worksheet, opt)
    if (callBackFn) callBackFn(data)
  }
}
// json转文件
// 入参:文件数组[] 头数组[] 文件名字符串
export const readJsonToFile = (data, header, fileName) => {
  console.info(data)
  let ws
  if (data && header) {
    ws = utils.json_to_sheet(data, { header: header })
  } else if (data) {
    ws = utils.json_to_sheet(data)
  }
  if (ws) {
    const wb = utils.book_new()
    utils.book_append_sheet(wb, ws, 'sheet1')
    writeFile(wb, fileName + '.xlsx')
  }
}

例子:

文本流转json

readJsonFromFile(this.file.raw, (data) => {
if (!data || data.length === 0) {
  this.$message.error('模板Excel无数据')
  this.file = null
  return
}

// 输出JSON
console.log(data)

// defval 给空单元格占位空字符串 raw: false 将输出的数字转为字符串
}, {defval: '', raw: false})

json转文件

const selectedItemList = []
letheaders = ''
let title = ''
headers = ['SPU编号', 'SPU名称', '类别']
this.activity.spuList.forEach(item => {
    const configItem = {}
    configItem[headers[0]] = item.productCode
    configItem[headers[1]] = item.name
    configItem[headers[2]] = item.categoryName
    selectedItemList.push(configItem)
})
title = '商品导出数据'
readJsonToFile(selectedItemList, headers, title)

你可能感兴趣的:(json,javascript)