Skip to content

Instantly share code, notes, and snippets.

@liranh85
Created June 29, 2019 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liranh85/a024ca2fc11caedf2754e61ac64d883a to your computer and use it in GitHub Desktop.
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
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