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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值