Created
October 26, 2022 11:15
-
-
Save Charlie-Hill/fac7f5bfa7b45f271188dc0a6c36da46 to your computer and use it in GitHub Desktop.
Typescript CSV Generator Class
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
interface ICsvRow { | |
items: Array<string> | |
} | |
interface ICsvData { | |
rows: Array<ICsvRow> | |
} | |
class CsvGenerator { | |
public headings: Array<string> = [] | |
public data: ICsvData = { rows: [] } | |
public fileName?: string | |
public fileDate?: boolean = true | |
private finalCsvData = '' | |
constructor (headings: Array<string>, csvData: ICsvData, fileName?: string, includeDate?: boolean) { | |
this.headings = headings | |
this.data = csvData | |
this.fileName = fileName ?? '' | |
this.fileDate = includeDate ?? true | |
this.generateCsv() | |
} | |
private generateDatedFileName (): string { | |
const date = new Date(Date.now()) | |
const dateString = date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear() | |
return dateString | |
} | |
private generateCsv (): void { | |
const csvMeta = 'data:text/csv;charset=utf-8,' | |
const csvHeadings = this.headings.join(',') + '\n' | |
let csvRows = '' | |
this.data.rows.map((row) => { | |
csvRows += row.items.join(',') + '\n' | |
}) | |
if (this.fileDate) { | |
this.fileName = this.fileName + '_' + this.generateDatedFileName() | |
} | |
this.finalCsvData = csvMeta + csvHeadings + csvRows | |
} | |
downloadCsv (): void { | |
const encodedUri = encodeURI(this.finalCsvData) | |
const link = document.createElement('a') | |
link.setAttribute('href', encodedUri) | |
link.setAttribute('download', this.fileName + '.csv') | |
document.body.appendChild(link) | |
link.click() | |
} | |
} | |
export { ICsvRow, ICsvData, CsvGenerator } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment