Last active
June 16, 2020 00:12
-
-
Save begoat/e355106f9c693e4145dc8dbaadcb31de to your computer and use it in GitHub Desktop.
js download array as csv
This file contains 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
// https://jsfiddle.net/3an24jmw/25/ | |
asUtf16 = (str) -> | |
buffer = new ArrayBuffer(str.length * 2) | |
bufferView = new Uint16Array(buffer) | |
bufferView[0] = 0xfeff | |
for i in [0..str.length] | |
val = str.charCodeAt(i) | |
bufferView[i + 1] = val | |
bufferView | |
makeExcelCsvBlob = (rows) -> | |
new Blob([asUtf16(toTsv(rows)).buffer], {type: "text/csv;charset=UTF-16"}) | |
toTsv = (rows) -> | |
escapeValue = (val) -> | |
if typeof val is 'string' | |
'"' + val.replace(/"/g, '""') + '"' | |
else if val? | |
val | |
else | |
'' | |
rows.map((row) -> row.map(escapeValue).join('\t')).join('\n') + '\n' | |
downloadExcelCsv = (rows, attachmentFilename) -> | |
blob = makeExcelCsvBlob(rows) | |
a = document.createElement('a') | |
a.style.display = 'none' | |
a.download = attachmentFilename | |
document.body.appendChild(a) | |
a.href = URL.createObjectURL(blob) | |
a.click() | |
URL.revokeObjectURL(a.href) | |
a.remove() | |
return | |
# Example: | |
rows = [ | |
['id', 'name', 'age'] | |
[1, 'John Doe', 43] | |
[2, 'Jane Doe', 42] | |
[3, 'Foo', 3] | |
] | |
window.exampleDownload = -> | |
downloadExcelCsv(rows, 'exported-data.csv') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment