如何在Node JS自动化中导出对象数组到csv?

nfs0ujit  于 2023-06-27  发布在  其他
关注(0)|答案(1)|浏览(115)

我有一个自动创建对象数组。如何转换数据并将其作为.csv文件下载到当前目录?

wn9m85ua

wn9m85ua1#

您可以通过以下方式使用csv-writer包(npm install csv-writer):

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));

相关问题