我有一个自动创建对象数组。如何转换数据并将其作为.csv文件下载到当前目录?
wn9m85ua1#
您可以通过以下方式使用csv-writer包(npm install csv-writer):
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));
1条答案
按热度按时间wn9m85ua1#
您可以通过以下方式使用
csv-writer
包(npm install csv-writer
):