Created
June 29, 2019 11:38
-
-
Save liranh85/a024ca2fc11caedf2754e61ac64d883a to your computer and use it in GitHub Desktop.
Utility functions to convert to CSV (using json2csv) and download the csv as a 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
import JSON2CSV from 'json2csv'; | |
export const convertToCSV = (arr: Array<any>) => { | |
const json2csvParser = new JSON2CSV.Parser(); | |
const csv = json2csvParser.parse(arr); | |
return csv; | |
}; | |
export const downloadCSV = (csv: string, fileName = 'download.csv') => { | |
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); | |
if (navigator.msSaveBlob) { // IE 10+ | |
navigator.msSaveBlob(blob, fileName); | |
} else { | |
var link = document.createElement('a'); | |
if (link.download !== undefined) { // feature detection | |
// Browsers that support HTML5 download attribute | |
var 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); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment