Last active
June 9, 2020 17:53
-
-
Save zergiocosta/ae85ebaf87773b527ee12a5aa0c90f4f to your computer and use it in GitHub Desktop.
Small TypeScript helper to export a html table content as a .csv file
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
export class CSVHelper { | |
public exportFromTable(table, filename): void { | |
let csv = [], | |
tableRows = table.querySelectorAll("tr") | |
for (let i = 0; i < tableRows.length; i++) { | |
let row = [], | |
cols = tableRows[i].querySelectorAll("td, th") | |
for (let j = 0; j < cols.length; j++) { | |
row.push(cols[j].innerHTML) | |
} | |
csv.push(row.join(",")) | |
} | |
this.downloadCsv( csv.join("\n"), filename ) | |
} | |
private downloadCsv(csv, filename): void { | |
let csvFile, | |
downloadLink, | |
date = this.currentDate() | |
csvFile = new Blob([csv], {type: "text/csv"}) | |
downloadLink = document.createElement("a") | |
downloadLink.download = date+'-'+filename | |
downloadLink.href = window.URL.createObjectURL(csvFile) | |
downloadLink.style.display = "none" | |
document.body.appendChild(downloadLink) | |
downloadLink.click() | |
} | |
private currentDate(): string { | |
let dateNow = new Date(Date.now()), | |
month = '' + (dateNow.getMonth() + 1), | |
day = '' + dateNow.getDate(), | |
year = dateNow.getFullYear() | |
if (month.length < 2) month = '0' + month | |
if (day.length < 2) day = '0' + day | |
return [year, month, day].join('-') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment