-
-
Save fanyer/4e7ad4022f7253b18e384e2432247901 to your computer and use it in GitHub Desktop.
Button Handler to download some JSON as CSV
This file contains hidden or 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
//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