Skip to content

Instantly share code, notes, and snippets.

@kawanet
Last active January 12, 2020 11:25
Show Gist options
  • Save kawanet/8438183 to your computer and use it in GitHub Desktop.
Save kawanet/8438183 to your computer and use it in GitHub Desktop.
Convert array of array to CSV (text/comma-separated-values) in JavaScript
/**
* Convert array of array to CSV (text/comma-separated-values)
*
* @param table {Array} array of array
* @returns {String} CSV
* @license MIT
* @see https://gist.github.com/kawanet/8438183
*/
function table_to_csv(table) {
var buf = table.map(function(row) {
row = row.map(function(str) {
if (str == null) {
str = "";
} else {
str += "";
}
if (str.search(/[,"\t\n\r]/) > -1) {
str = '"' + str.replace(/"/g, '""') + '"';
}
return str;
});
return row.join(",") + "\x0D\x0A";
});
return buf.join("");
}
if ("undefined" !== typeof module) module.exports = table_to_csv;
/**
* Convert array of array to CSV (text/comma-separated-values)
*
* @param table {Array} array of array
* @returns {String} CSV
* @license MIT
* @see https://gist.github.com/kawanet/8438183
*/
export function table_to_csv(table: string[][]) {
return table.map(row => {
row = row.map(str => {
if (str == null) {
str = "";
} else {
str += "";
}
if (str.search(/[,"\t\n\r]/) > -1) {
str = '"' + str.replace(/"/g, '""') + '"';
}
return str;
});
return row.join(",") + "\x0D\x0A";
}).join("");
}
@kawanet
Copy link
Author

kawanet commented Jan 15, 2014

これも今まで何度も書いたことがあるよねシリーズ。
二次元テーブル(配列の配列)を CSV に変換する JavaScript。
Windows でダウンロードしたいので、改行コードを \r\n にしてみた。
ブラウザ上で UTF-8 から CP932 に変換するためには、iconv-cp932 をどうぞ。
https://github.com/kawanet/iconv-cp932

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment