nodejs工具脚本json转excel

发布于:2024-04-23 ⋅ 阅读:(21) ⋅ 点赞:(0)

json转excel

主要使用 sheetjs

vim convertJsonToExcel.js 封装转换方法

import fs from 'fs';
import XLSX from 'xlsx';

/**
 * 扁平化嵌套json对象
 * @param {Object} jsonObj
 * @param {String} prefix
 * @returns
 */
export function flattenKeys(jsonObj, prefix = '') {
  const result = {};

  for (const key in jsonObj) {
    const value = jsonObj[key];
    const newKey = prefix ? `${prefix}/${key}` : key;

    if (typeof value === 'object' && value !== null) {
      Object.assign(result, flattenKeys(value, newKey));
    } else {
      result[newKey] = value;
    }
  }

  return result;
}

/**
 * 转换 json 对象数据
 * @param {Object} data
 * @returns
 */
export function adaptData(data) {
  const jsonDataFlat = flattenKeys(data)
  let result = []
  let count = {}
  //excel: key	module	source	context
  Object.entries(jsonDataFlat).forEach(([key, value]) => {
    let keyArr = key.split('/')
    let item = {
      key: keyArr.join('.'),
      // module: keyArr.slice(0, -1).join('/'),
      module: 'data',
      source: value,
      context: '',
    }
    result.push(item)
  })
  return result
}
export const convertJsonToExcel = async (jsonFilePath, excelFilePath) => {
  const jsonData = JSON.parse(await fs.promises.readFile(jsonFilePath, 'utf8'));
  /**
   * @example data
   * ```
   [
    { Name: "Bill Clinton", Index: 42 },
    { Name: "GeorgeW Bush", Index: 43 },
  ]
   * ```
   */
  const dataArray = adaptData(jsonData)
  const headerArr = [['i18n key json']]

  const worksheet = XLSX.utils.json_to_sheet(dataArray, {origin: 'A2'});
  XLSX.utils.sheet_add_aoa(worksheet, headerArr, {origin: 'A1'})
  // 合并单元格
  worksheet['!merges'] = [
    // s:start, e: end, c: column, r: row
    {
      s: {c: 0, r: 0},
      e: {c: 4, r: 0}
    }
  ]

  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  XLSX.writeFile(workbook, excelFilePath);
}

调用转换方法
vim convert.js

import fs from 'fs';
import {convertJsonToExcel} from './convertJsonToExcel.js'
import jsonData from './data.js'

// 实际使用不需要此步骤,已经把js对象转换成json文件
fs.writeFileSync('data.json', JSON.stringify(jsonData), 'utf-8')
convertJsonToExcel('data.json', 'output.xlsx')

json对象示例

{
    "common": {
        name: '名称'
    }
}

在这里插入图片描述