30
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsでCSV出力(npm csv-writer)

Last updated at Posted at 2018-08-25

概要

#CSV出力サンプルコード

csvwrite.js
const {createObjectCsvWriter} = require('csv-writer');
const csvfilepath =  __dirname+'/message.csv'
const csvWriter = createObjectCsvWriter({
    path: csvfilepath,
    header: [
        // {id: 'name', title: 'NAME'},      //Headerつける場合
        // {id: 'lang', title: 'LANGUAGE'}  //Headerつける場合
        'name','lang' //Headerなしの場合
    ],
    encoding:'utf8',
    append :false, // append : no header if true
});
// Data for CSV
const records = [
    {name: 'Bob',  lang: 'French, English'},
    {name: 'Mary', lang: 'English'},
    {name: 'Alef', lang: 'English', age:23},
];
//Write CSV file
csvWriter.writeRecords(records)       // returns a promise
    .then(() => {
        console.log('...Done');
    });

作成されるCSV

message.csv
Bob,"French, English"
Mary,English
Alef,English

(本題?)Headerを自動でつけたい [Object.key]

Headerを出力したいObject配列から作成する。

//ObjectのKeyを{item:key, title:key}配列で返す関数の例
function makeHeader(obj){
    let header=[]
    header = Object.keys(obj).map( v => ({ id:v, title:v }) ) 
    return header;
}

ヘッダー自動生成サンプル

csvwrite_autoheader.js

const {createObjectCsvWriter} = require('csv-writer');
const csvfilepath =  __dirname+'/message.csv'

// Data for CSV
const records = [
    {name: 'Bob',  lang: 'French, English'},
    {name: 'Mary', lang: 'English'},
    {name: 'Alef', lang: 'English', age:23},
];

// Header Create from data
const csvWriter2 = createObjectCsvWriter({
    path:csvfilepath,
    // header: Object.keys(records[0])           // Headerなし 
    header:Object.keys(records[0]).map( v => ({ id:v, title:v })) // Header==Keys
})

//Write CSV
csvWriter2.writeRecords(records)       // returns a promise
    .then(() => {
        console.log('...Done');
    });

作成されるCSV

csv
name,lang
Bob,"French, English"
Mary,English
Alef,English
30
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?