Last active
January 12, 2020 11:25
-
-
Save kawanet/8438183 to your computer and use it in GitHub Desktop.
Convert array of array to CSV (text/comma-separated-values) in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
これも今まで何度も書いたことがあるよねシリーズ。
二次元テーブル(配列の配列)を CSV に変換する JavaScript。
Windows でダウンロードしたいので、改行コードを \r\n にしてみた。
ブラウザ上で UTF-8 から CP932 に変換するためには、iconv-cp932 をどうぞ。
https://github.com/kawanet/iconv-cp932