英文:
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论