Skip to content

Instantly share code, notes, and snippets.

@shavit
Created July 4, 2012 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shavit/3049455 to your computer and use it in GitHub Desktop.
Save shavit/3049455 to your computer and use it in GitHub Desktop.
Export HTML table to CSV using javascript.
$("#btnExportHTMLToCSV").click((event) ->
$table = $("#tableToExport")
if !$table
return false
headers = []
csv = ""
$table.find("thead th").each(() ->
$th = $(this)
text = $th.text()
header = '"'+text+'"'
headers.push(header)
)
csv += headers.join(',')+"\n"
$table.find("tbody tr").each(() ->
tdIndex = 0
$(this).find("td").each(() ->
row = $(this).html()
tdIndex += 1
if(tdIndex < 4)
row += ','
else
row += "\n"
tdIndex = 1
csv += row
console.log(tdIndex)
)
)
# Delete the line below in production
console.log(csv)
# Change the '/export/' to the url
# You need to pass the GET parameters to the client
# with CSV headers. Maybe you want to encode it
# before sending it.
window.open(location.origin+"/export/"+csv)
)
@sylvery
Copy link

sylvery commented May 3, 2022

thanks a lot. this really helped me brush up on my vanila javascript. here's a suggestion to improve this you could have something like this:
$table.getElementsByTagName('tr').forEach(element => { tdIndex = 0; element.getElementsByTagName('td').forEach(tdElement => { row = tdElement.innerText; tdIndex += 1; if (tdIndex < headers.length) { row += ','; } else{ row += '\n'; tdIndex =1 } csv += row; }) })
note: headers was defined in an earlier line from the original code...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment