如何在Node.js自动化中将对象数组导出为CSV?

huangapple go评论75阅读模式
英文:

How to export array of objects to csv in Node JS automation?

问题

如何将这些数据转换并下载为一个.csv文件到当前目录?

英文:

I have an automation which creates an array of objects. How can I convert that data and download it as a .csv file to the current directory?

答案1

得分: 1

你可以使用csv-writer包(npm install csv-writer)如下所示:

const createCsvWriter = require('csv-writer').createObjectCsvWriter;

// 假设你有一个名为'data'的对象数组
const data = [
  { name: 'A', age: 10, email: 'a@a.com' },
  { name: 'B', age: 20, email: 'b@b.com' },
  { name: 'C', age: 30, email: 'c@c.com' }
];

// 定义CSV文件的标题
const csvHeaders = [
  { id: 'name', title: 'Name' },
  { id: 'age', title: 'Age' },
  { id: 'email', title: 'Email' }
];

// 创建一个CSV写入实例
const csvWriter = createCsvWriter({
  path: 'output.csv', // 输出CSV文件的路径
  header: csvHeaders
});

// 将数据写入CSV文件
csvWriter.writeRecords(data)
  .then(() => console.log('CSV文件已成功写入。'))
  .catch((error) => console.error('写入CSV文件时发生错误:', error));
英文:

You can use the csv-writer package (npm install csv-writer) in the following way:

const createCsvWriter = require('csv-writer').createObjectCsvWriter;

// Assuming you have an array of objects named 'data'
const data = [
  { name: 'A', age: 10, email: 'a@a.com' },
  { name: 'B', age: 20, email: 'b@b.com' },
  { name: 'C', age: 30, email: 'c@c.com' }
];

// Define the headers for your CSV file
const csvHeaders = [
  { id: 'name', title: 'Name' },
  { id: 'age', title: 'Age' },
  { id: 'email', title: 'Email' }
];

// Create a CSV writer instance
const csvWriter = createCsvWriter({
  path: 'output.csv', // Path to the output CSV file
  header: csvHeaders
});

// Write the data to the CSV file
csvWriter.writeRecords(data)
  .then(() => console.log('CSV file has been written successfully.'))
  .catch((error) => console.error('Error writing CSV file:', error));

huangapple
  • 本文由 发表于 2023年6月22日 07:58:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527832.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定