4
3

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.

Sails.jsでcsv出力する方法

Last updated at Posted at 2017-05-25

json2csvを使えば楽

インストール

npm install json2csv --save

csvデータ作成

sample.js
var json2csv = require('json2csv');
var fields = ['id', 'title'];
var data = {
  "id": 1,
  "title": "test",
};
var csv = json2csv({data: data, fields: fields});

フィールドのカスタマイズもできる

sample.js
var fieldNames = ['番号', 'タイトル'];
var csv = json2csv({data: data, fields: fields, fieldNames: fieldNames});

その他詳細な機能はgithubドキュメント参照。

日本語エクセル対応

エクセルで読み出したいので、charsetをshift_jisにしたい。

iconv_liteを使う

npm install iconv-lite --save
sample.js
var iconv = require('iconv-lite');
sample.js
var csv = iconv.encode(csv, "Shift_JIS");

送信

sailsなのでexpress.jsに準じる。

sample.js
var filename = 'file.csv'

res.attachment(filename);
var csv = iconv.encode(csv, "Shift_JIS");
res.send(csv);

これで日本語Excel対応のCSVファイルがレスポンスされます。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?