• 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')
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    例子:

    文本流转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})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    结构体、枚举、位段、联合体详解
    虚拟机JVM
    大型语言模型中的幻觉研究综述:原理、分类、挑战和未决问题11.15+11.16+11.17
    酷克数据发布HD-SQL-LLaMA模型,开启数据分析“人人可及”新时代
    NAT技术研究
    美容院如何体现差异化服务?
    一本通1057;简单计算器(2)
    WordPress多语言翻译插件小语种互译
    TypeScript_抓取酒店价格数据
    Vue2(十一):脚手架配置代理、github案例、插槽
  • 原文地址:https://blog.csdn.net/weixin_34403976/article/details/133740584