Last active
June 25, 2022 18:44
-
-
Save mauricio-testa/11a894df5c98e7d74ef54a32943df0e3 to your computer and use it in GitHub Desktop.
htmlTable2Spreadsheet
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
/** | |
* Convert an html table to a spreadsheet and download it | |
* | |
* @param {String} selector - Selector of table | |
* @param {String} format - xls or csv | |
* | |
* Usage | |
* htmlTable2Spreadsheet('.table', 'xls').download() | |
*/ | |
class htmlTable2Spreadsheet { | |
constructor(selector = 'table', format = 'xls') { | |
this.selector = selector | |
this.format = format | |
this.content = ''; | |
this._make() | |
} | |
_make() { | |
const divider = this.format == 'csv' ? ',' : ';' | |
const element = document.querySelector(this.selector) | |
element.querySelectorAll('tr').forEach(row => | |
this.content += [...row.querySelectorAll('td, th')].map(td => | |
td.innerHTML.trim() | |
).join(divider) + '\n' | |
) | |
return this | |
} | |
download() { | |
window.open('data:text/csv;charset=utf-8,' + escape(this.content)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment