读取Excel导出JSON或导出YAML文件

445 阅读1分钟

读取同级目录excel下的所有文件

  • 导出json node index.js json
  • 导出yaml node index.js yaml
const fs = require('fs')
const path = require('path')
const xlsx = require('node-xlsx')
const yaml = require('js-yaml')

const arguments = process.argv.splice(2)
const type = arguments[0] ?? 'json' // 默认转出 json

const reverse = ['branch_code字典', 'vendor字典'] // 要字段对调的的 excel 表

const entry = './excel' // excel 文件目录
const dirInfo = fs.readdirSync(entry)
let target = ''

const writeFileTypeMap = {
  json: value => JSON.stringify(value, '', '\t'),
  yaml: value => yaml.dump(value)
}

dirInfo.forEach(excel => {
  const location = path.join(entry, excel)
  const sheets = xlsx.parse(location)
  target = `./${type}/${excel.split('.')[0]}/`

  try {
    fs.readdirSync(`./${type}`)
  } catch (error) {
    fs.mkdirSync(`./${type}`)
  }

  try {
    fs.readdirSync(target)
  } catch (error) {
    fs.mkdirSync(target)
  }

  sheets.forEach(item => {
    let obj = {}
    obj = Object.fromEntries(
      item.data.flatMap((itm, idx) =>
        idx > 0 && JSON.stringify(itm) !== '[]'
          ? [reverse.includes(item.name) ? itm.reverse() : itm]
          : []
      )
    )

    fs.writeFileSync(`${target}${item.name}.${type}`, writeFileTypeMap[type](obj))
  })
})