generateCsv.ts
· 935 B · TypeScript
Raw
const generateCsv = (
rows: (string | number)[][],
headers: string[],
filename: string,
as: "download" | "contents" | "downloadInPlace",
): string | undefined => {
if (typeof document === "undefined" && as !== "contents") {
throw new Error(
"This method does not support being used in a non-browser environment.",
);
}
const csvContent = [headers, ...rows]
.map((rowArray) => rowArray.join(","))
.join("\r\n");
if (as === "contents") return csvContent;
if (as === "download") return `data:text/csv;charset=utf-8,${csvContent}`;
const encodedUri = encodeURI(`data:text/csv;charset=utf-8,${csvContent}`);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", `${filename}.csv`);
document.body.appendChild(link); // Required for FF
link.click();
document.body.removeChild(link); // Clean up the DOM
return undefined;
};
export default generateCsv;
1 | const 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 | |
31 | export default generateCsv; |
32 |