Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.