在TypeScript中将JSON数据转换为Excel工作表

xj3cbfub  于 2023-03-13  发布在  TypeScript
关注(0)|答案(1)|浏览(123)

我需要使用TypeScript将JSON数据转换为Excel工作表。
我想把下面的数据转换成.xlsx file

const JsonData = [
  {
  "email": "abc@gmail.com",
  "industry":"IT",
  "role": "Developer",
  "firstName": "Shubham",
  "lastName": "Verma",
  "title": "Software Engineer",
  "country": "India"
  },
  {
  "email": "XYG@gmail.com",
  "industry":"IT",
  "role": "Developer",
  "firstName": "Ankit",
  "lastName": "Kumar",
  "title": "Software Engineer",
  "country": "India"
  }
]

我探索了互联网和StackOverflow,但无法找到正确和准确的解决方案。这就是为什么问这里。有很多解决方案的Nodejs和javaScript,但没有TypeScript

yzuktlbb

yzuktlbb1#

这就是我使用JSON数据创建example.xlsx文件的方法。

const { readFile, writeFile } = require('fs').promises;
const { json2csvAsync } = require('json-2-csv');

async function writeCSVFile (fileName, data) {
  await writeFile(fileName, data, 'utf8');
}

export const createExcel = async (fileName = '', dataToWrite: any) => {
  try {
    const data = JSON.parse(dataToWrite)
    const csv = await json2csvAsync(data);
    await writeCSVFile(fileName, csv);
    console.log(`Successfully converted ${fileName}!`);
  }
  catch (err) {
    console.log(err);
    return [];
  }
}

如何从不同文件调用函数:

const JsonData = [
      {
      "email": "abc@gmail.com",
      "industry":"IT",
      "role": "Developer",
      "firstName": "Shubham",
      "lastName": "Verma",
      "title": "Software Engineer",
      "country": "India"
      },
      {
      "email": "XYG@gmail.com",
      "industry":"IT",
      "role": "Developer",
      "firstName": "Ankit",
      "lastName": "Kumar",
      "title": "Software Engineer",
      "country": "India"
      }
   ];



 const fileName = 'result.xlsx';
 const fileResult = await createExcel(fileName, JSON.stringify(JsonData));

相关问题