Created
June 7, 2014 21:05
-
-
Save isakb/f60c5e5273eed52973e5 to your computer and use it in GitHub Desktop.
Download JavaScript array as Excel CSV for any version of Excel
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
# See http://jsfiddle.net/isak_b/hp6fj/ for live demo. | |
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 | |
# (assuming HTML like: <button onclick="exampleDownload()">Download</button>): | |
rows = [ | |
['id', 'name', 'age'] | |
[1, 'John Doe', 43] | |
[2, 'Jane Doe', 42] | |
[3, 'Foo', 3] | |
] | |
window.exampleDownload = -> | |
downloadExcelCsv(rows, 'exported-data.csv') |
Hi Ashish,
yes, you are allowed to use it, and sorry for the late reply!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Isak, I have requirement in my project where I need to convert Javascript object to csv.Your code is just awesome and after converting to javascript its work as expected for me. I could not find any licensing information for this code. So, can I use it in my project?
-Ashish Sharma