node.jsでCSVを作成するには

node-csvを使って、CSVファイルを作成する方法です。

インストール

npm init
npm install csv --save

文字列の配列をCSVに変換する(callback)

callbackを使ったTypeScriptのサンプルコードです。

csv.stringify()の引数に、文字列の配列とコールバック関数を設定します。
CSVに変換された文字列がコールバック関数の引数outputになります。

import * as csv from "csv";

const input = [ [ "1", "2", "3", "4" ], [ "a", "b", "c", "d" ] ];
csv.stringify(input, function(err, output){
    console.log(output);
});

実行結果

1,2,3,4
a,b,c,d

文字列の配列をCSVに変換する(stream)

streamを使ったTypeScriptのサンプルコードです。

write()メソッドの引数に文字列の配列を指定します。

実行すると、readableイベントで変換された文字列を受け取ることができます。
read()メソッドで各行の文字列を受け取ります。

import * as csv from "csv";

let data = "";
const stringifier = csv.stringify({ delimiter: ":" })
stringifier.on("readable", function () {
    let row;
    while (row = stringifier.read()) {
        data += row;
    }
});
stringifier.on("error", function (err) {
    console.log(err.message);
});
stringifier.on("finish", function () {
    console.log(data);
});
stringifier.write(["1", "2", "3", "4"]);
stringifier.write(["a", "b", "c", "d"]);
stringifier.end();

オブジェクトの配列をCSVに変換する

引数にオブジェクトを指定することもできます。

import * as csv from "csv";

const input = [
    {Rider: "MARQUEZ Marc", Nation: "SPA", Points: "298"},
    {Rider: "ROSSI Valentino", Nation: "ITA", Points: "249"},
    {Rider: "LORENZO Jorge", Nation: "SPA", Points: "233"},
];
const columns = {
Rider: "Rider",
Nation: "Nation",
Points: "Points",
};
csv.stringify(input, { header: true, columns: columns }, function(err, output){
    console.log(output);
});

実行結果

MARQUEZ Marc,SPA,298
ROSSI Valentino,ITA,249
LORENZO Jorge,SPA,233

headerオプションを指定すると、プロパティ名が列名になります。

import * as csv from "csv";

const input = [
    {Rider: "MARQUEZ Marc", Nation: "SPA", Points: "298"},
    {Rider: "ROSSI Valentino", Nation: "ITA", Points: "249"},
    {Rider: "LORENZO Jorge", Nation: "SPA", Points: "233"},
];
csv.stringify(input, { header: true}, function(err, output){
    console.log(output);
});

実行結果

Rider,Nation,Points
MARQUEZ Marc,SPA,298
ROSSI Valentino,ITA,249
LORENZO Jorge,SPA,233

列名を設定したいときは、columnsオプションを使用します。

import * as csv from "csv";

const input = [
    {Rider: "MARQUEZ Marc", Nation: "SPA", Points: "298"},
    {Rider: "ROSSI Valentino", Nation: "ITA", Points: "249"},
    {Rider: "LORENZO Jorge", Nation: "SPA", Points: "233"},
];
const columns = {
Rider: "選手",
Nation: "国",
Points: "ポイント",
};
csv.stringify(input, { header: true, columns: columns}, function(err, output){
    console.log(output);
});

実行結果

選手,国,ポイント
MARQUEZ Marc,SPA,298
ROSSI Valentino,ITA,249
LORENZO Jorge,SPA,233

delimiterオプション

delimiterオプションで区切り文字を変更できます。

次の例ではタブ区切りで出力します。

import * as csv from "csv";

const input = [ [ "1", "2", "3", "4" ], [ "a", "b", "c", "d" ] ];
csv.stringify(input, {delimiter: "\t"}, function(err, output){
    console.log(output);
});

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください