Created
August 18, 2022 22:57
-
-
Save reatlat/7fc06bd5f4d6e6305a563191cc3afaba to your computer and use it in GitHub Desktop.
Quick and simple export target | https://stackoverflow.com/questions/15547198/export-html-table-to-csv-using-vanilla-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
<a href="#" onclick="download_table_as_csv('my_id_table_to_export');">Download as CSV</a> |
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
// Quick and simple export target #table_id into a csv | |
function download_table_as_csv(table_id, separator = ',') { | |
// Select rows from table_id | |
var rows = document.querySelectorAll('table#' + table_id + ' tr'); | |
// Construct csv | |
var csv = []; | |
for (var i = 0; i < rows.length; i++) { | |
var row = [], cols = rows[i].querySelectorAll('td, th'); | |
for (var j = 0; j < cols.length; j++) { | |
// Clean innertext to remove multiple spaces and jumpline (break csv) | |
var data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ') | |
// Escape double-quote with double-double-quote (see https://stackoverflow.com/questions/17808511/properly-escape-a-double-quote-in-csv) | |
data = data.replace(/"/g, '""'); | |
// Push escaped string | |
row.push('"' + data + '"'); | |
} | |
csv.push(row.join(separator)); | |
} | |
var csv_string = csv.join('\n'); | |
// Download it | |
var filename = 'export_' + table_id + '_' + new Date().toLocaleDateString() + '.csv'; | |
var link = document.createElement('a'); | |
link.style.display = 'none'; | |
link.setAttribute('target', '_blank'); | |
link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string)); | |
link.setAttribute('download', filename); | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment