Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
Created June 28, 2022 14:12
Show Gist options
  • Save dmorosinotto/c4ca1d513521eebc09a0ab3096ccac09 to your computer and use it in GitHub Desktop.
Save dmorosinotto/c4ca1d513521eebc09a0ab3096ccac09 to your computer and use it in GitHub Desktop.
Export to CSV + File download via JS
public csvData<T>(arr: T[], keys: Array<{ field: string, title?: string}> = []): string {
//MD EXPORT
//CONVERTE ARRAY DATI -> CSV CON PRIMA RIGA NOME CAMPI
const sep = ";";
if (arr && arr.length) {
if (keys == null || keys.length == 0) keys = Object.keys(arr[0]).map(k => ({ field: k, title: k }));
const titles = keys.map(key => key.title || key.field);
let csv = arr.map(obj => {
let row: string[] = [];
keys.forEach(key => {
let v = key.field.split(".").reduce((obj,k)=>obj && obj[k], obj);
if (v == null) row.push("");
else if (typeof v == "string") row.push(`"${v.replace('"', '""')}"`);
else row.push(`${v}`);
});
return row.join(sep);
})
//let head = Object.keys(obj).join(sep); csv.unshift(head);
csv.unshift(titles.join(sep));
return csv.join("\n");
} else return "NO DATA TO EXPORT";
}
public downloadFile(data: any, name: string = "storico.csv") {
//MD EXPORT
//SOURCE CODE PRESO DA www.youtube.com/watch?v=io2blfAlO6E
const blob = new Blob([data], { type: "octet-stream" }); //application/octet-stream
const href = URL.createObjectURL(blob);
this.startDownload(href, name);
URL.revokeObjectURL(href);
//a.remove();
}
public startDownload(href: string, name: string) {
// @ts-ignore
const a: HTMLAnchorElement = Object.assign(document.createElement("a"), {
href,
style: "display:none",
download: name
});
document.body.appendChild(a);
a.click();
a.remove();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment