Last active
April 18, 2021 07:01
-
-
Save changhuixu/de092ee55a9e115abba988910bd68d41 to your computer and use it in GitHub Desktop.
Export Objects Array as CSV using TypeScript
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 CsvDataService { | |
static exportToCsv(filename: string, rows: object[]) { | |
if (!rows || !rows.length) { | |
return; | |
} | |
const separator = ','; | |
const keys = Object.keys(rows[0]); | |
const csvContent = | |
keys.join(separator) + | |
'\n' + | |
rows.map(row => { | |
return keys.map(k => { | |
let cell = row[k] === null || row[k] === undefined ? '' : row[k]; | |
cell = cell instanceof Date | |
? cell.toLocaleString() | |
: cell.toString().replace(/"/g, '""'); | |
if (cell.search(/("|,|\n)/g) >= 0) { | |
cell = `"${cell}"`; | |
} | |
return cell; | |
}).join(separator); | |
}).join('\n'); | |
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); | |
if (navigator.msSaveBlob) { // IE 10+ | |
navigator.msSaveBlob(blob, filename); | |
} else { | |
const link = document.createElement('a'); | |
if (link.download !== undefined) { | |
// Browsers that support HTML5 download attribute | |
const url = URL.createObjectURL(blob); | |
link.setAttribute('href', url); | |
link.setAttribute('download', filename); | |
link.style.visibility = 'hidden'; | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
} | |
} | |
} | |
} |
BipulRaman
commented
Jul 5, 2020
•
Set the data type of row.
rows.map( (row: any) => {
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment