Skip to content

Instantly share code, notes, and snippets.

@mauricio-testa
Last active June 25, 2022 18:44
Show Gist options
  • Save mauricio-testa/11a894df5c98e7d74ef54a32943df0e3 to your computer and use it in GitHub Desktop.
Save mauricio-testa/11a894df5c98e7d74ef54a32943df0e3 to your computer and use it in GitHub Desktop.
htmlTable2Spreadsheet
/**
* 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