Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Created October 30, 2013 00:06
Show Gist options
  • Save joshmcarthur/7224968 to your computer and use it in GitHub Desktop.
Save joshmcarthur/7224968 to your computer and use it in GitHub Desktop.
Export an HTML table to a CSV file using HTMl5 Blob object, with data URI fallback
$.fn.exportToCsv = ->
export_element = $( $(this).data('export-target') )
csv_string = csvStringFrom(export_element)
if Blob
$(this).prop(
download: csvFilename(),
href: URL.createObjectURL(new Blob([csv_string], type: 'text/csv'))
)
else
data_uri_header = 'data:text/csv;charset=UTF-8,'
window.location = data_uri_header + encodeURIComponent(csv_string)
csvFilename = (prefix = "export") ->
date = new Date()
date_parts = [
date.getFullYear(),
date.getMonth(),
date.getDay(),
date.getHours(),
date.getMinutes()
]
([prefix].concat date_parts).join('-') + ".csv"
csvStringFrom = (element) ->
if element.is('table')
csv = ""
headers = []
body = []
element.find('thead > tr > th').each ->
headers.push($(this).text())
element.find('tbody > tr').each ->
row = []
$(this).find('td').each ->
row.push $(this).text()
body.push(row.join(','))
if headers.length
csv += (headers.join(",") + "\n")
csv += body.join("\n")
return csv
else
element.text()
$ ->
$('a#export-report').click ->
$(this).exportToCsv()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment