Skip to content

Instantly share code, notes, and snippets.

@royashbrook
Created September 4, 2020 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save royashbrook/5535c7bee7dd1710b50e592d14e52461 to your computer and use it in GitHub Desktop.
Save royashbrook/5535c7bee7dd1710b50e592d14e52461 to your computer and use it in GitHub Desktop.
Button Handler to download some JSON as CSV
//bind onclick to downloadcsv.
//o should be the json you want to turn into a table
//h should be a string array for the header row, or this can be null and it will use the keys from the first record
//n is the name of the file, csv will be appended. if omitted it will just be 'data.csv'
export const downloadcsv = (o,h,n = 'data') => {
downloadFile( toCSV(o,h) , n + '.csv', 'text/csv' );
}
const toCSV = (o,h) => {
const a = (v) => `"${v.join(`","`)}"`
let csv = []
csv.push(h ? h : Object.keys(o[0]));
o.forEach(x=>csv.push(a(Object.values(x))))
return csv.join("\n")
}
const downloadFile = (fileContents,fileName, fileType) => {
var blob = new Blob([fileContents], { type: fileType });
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.display = "none";
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