Last active 1720540765

generateCsv.ts Raw
1const generateCsv = (
2 rows: (string | number)[][],
3 headers: string[],
4 filename: string,
5 as: "download" | "contents" | "downloadInPlace",
6): string | undefined => {
7 if (typeof document === "undefined" && as !== "contents") {
8 throw new Error(
9 "This method does not support being used in a non-browser environment.",
10 );
11 }
12
13 const csvContent = [headers, ...rows]
14 .map((rowArray) => rowArray.join(","))
15 .join("\r\n");
16
17 if (as === "contents") return csvContent;
18 if (as === "download") return `data:text/csv;charset=utf-8,${csvContent}`;
19 const encodedUri = encodeURI(`data:text/csv;charset=utf-8,${csvContent}`);
20 const link = document.createElement("a");
21 link.setAttribute("href", encodedUri);
22 link.setAttribute("download", `${filename}.csv`);
23 document.body.appendChild(link); // Required for FF
24
25 link.click();
26 document.body.removeChild(link); // Clean up the DOM
27
28 return undefined;
29};
30
31export default generateCsv;
32