Created
July 4, 2012 20:44
-
-
Save shavit/3049455 to your computer and use it in GitHub Desktop.
Export HTML table to CSV using javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("#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
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...