Download Array as Excel CSV

Example code for how to export tabular data (array of arrays) as an Excel CSV that can be imported into all versions of Excel known to man. The first row is assumed to be the table header. This code only works in modern browsers.

by oktaviardi pratama

HTML

<button onclick="exampleDownload()">Download Excel CSV</button>

JavaScript

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')