Created
March 11, 2021 15:00
-
-
Save miwebguy/18b5376c9fe5fab34c97c7287ae120a8 to your computer and use it in GitHub Desktop.
VanillaJS Table to CSV Export
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
| function table2csv(table_id) { | |
| // based on https://stackoverflow.com/questions/15547198/export-html-table-to-csv | |
| // Quick and simple export target #table_id into a csv | |
| var 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