Created
January 8, 2014 03:39
-
-
Save AndrewReitz/8311393 to your computer and use it in GitHub Desktop.
Download a table on a website with JavaScript
This file contains 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
// Place to store all the strings for the CSV | |
var stringBuilder = []; | |
// Get the table, this one happens to be adminlist | |
// Could probably make the more generic | |
var table = document.getElementsByClassName('adminlist')[0]; | |
var tbody = table.getElementsByTagName('tbody')[0] | |
var rows = tbody.getElementsByTagName('tr'); | |
// Loop through each row | |
for (var i = 0; i < rows.length; i++) { | |
// Grab the data from each row and add it to the | |
// temporary row | |
var data = rows[i].getElementsByTagName('td'); | |
var tempRow = []; | |
for (var j = 0; j < data.length; j++) { | |
tempRow.push('"' + data[j].innerText + '"'); | |
} | |
// Join all the rows into a string with a , | |
// to complete the csv row | |
stringBuilder.push(tempRow.join(',')); | |
} | |
// Create a blob place all the content into it | |
// and then do a silly hack to download it | |
var myBlob = new Blob([stringBuilder.join('\n')], {"type": "text\/plain"}); | |
var myLink = document.createElement('a'); | |
document.body.appendChild(myLink); | |
myLink.href = window.URL.createObjectURL(myBlob); | |
myLink.download = "users.csv"; | |
myLink.click();; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment