Skip to content

Instantly share code, notes, and snippets.

@isakb
Created June 7, 2014 21:05
Show Gist options
  • Save isakb/f60c5e5273eed52973e5 to your computer and use it in GitHub Desktop.
Save isakb/f60c5e5273eed52973e5 to your computer and use it in GitHub Desktop.
Download JavaScript array as Excel CSV for any version of Excel
# 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')
@a3986
Copy link

a3986 commented Jun 9, 2014

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

@isakb
Copy link
Author

isakb commented Feb 19, 2015

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