const LINE_BREAK = "\r\n"; export default class Exporter { csv(data: Array | object) { let convertToString = (d: Array | object) => { var output = ""; if (d instanceof Array) { let hasWrittenColumn = false; d.forEach((datum) => { let row = ""; if (typeof datum === "object") { let attributes = Object.keys(datum); if (!hasWrittenColumn) { output += attributes.join(",") + LINE_BREAK; hasWrittenColumn = true; } attributes.forEach((attribute, i) => { row += datum[attribute]; if (i !== attributes.length - 1) { row += ","; } }); } else { row = datum.toString(); } output += row + LINE_BREAK; }); return output; } Object.keys(data).forEach((attribute) => { output += attribute + LINE_BREAK; output += convertToString(data[attribute]) + LINE_BREAK; }); return output; }; this.export([convertToString(data)], "text/csv;charset=utf-8;", "csv"); } async xlsx() { const JSZip = (await import("jszip")).default; // Note the '.default' const data = [ { name: "John Doe", age: 28, email: "john.doe@example.com" }, { name: "Jane Doe", age: 22, email: "jane.doe@example.com" }, ]; const xmlHeader = ''; const workbookXML = `${xmlHeader} `; let worksheetXML = `${xmlHeader} Name Age Email `; data.forEach((item) => { worksheetXML += ` ${item.name} ${item.age} ${item.email} `; }); worksheetXML += ``; const relsXML = `${xmlHeader} `; const contentTypesXML = `${xmlHeader} `; const zip = new JSZip(); zip.file("xl/workbook.xml", workbookXML); zip.file("xl/worksheets/sheet1.xml", worksheetXML); zip.file( "_rels/.rels", `${xmlHeader} ` ); zip.file("xl/_rels/workbook.xml.rels", relsXML); zip.file("[Content_Types].xml", contentTypesXML); let content = await zip.generateAsync({ type: "blob" }); this.export( content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx" ); } json(data: Array | object) { this.export( [JSON.stringify(data, null, 2)], "application/json", "json" ); } export(data: Blob | Array, type: string, extension: string) { let url = window.URL.createObjectURL( data instanceof Blob ? data : new Blob(data, { type: "text/csv;charset=utf-8;", }) ); var a = document.createElement("a"); a.setAttribute("href", url); a.setAttribute( "download", new Date().toLocaleString() + "." + extension ); a.click(); } }