Skip to content

Instantly share code, notes, and snippets.

@adrianhorning08
Created January 5, 2024 23:35
Show Gist options
  • Save adrianhorning08/bdd53f931dff22f2a0009c6e11a27f82 to your computer and use it in GitHub Desktop.
Save adrianhorning08/bdd53f931dff22f2a0009c6e11a27f82 to your computer and use it in GitHub Desktop.
Create CSV on frontend
export function createCSV(data, fileName) {
const headers = Object.keys(data[0]);
const csvContent = [
headers.join(","),
...data.map((row) =>
headers
.map((header) => {
const value = row[header];
if (value === null) return "null";
if (typeof value === "string") {
// Wrap all fields, including those without commas, in double quotes
return `"${value.replace(/"/g, '""')}"`;
}
return value;
})
.join(",")
),
].join("\n");
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a");
if (navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(blob, fileName);
} else {
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName || "data.csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment