Skip to content

Instantly share code, notes, and snippets.

@mals14
Forked from adrianhorning08/index.js
Created January 13, 2024 23:39
Show Gist options
  • Save mals14/eb8acd11f9075dc96b4caaca3c502cc8 to your computer and use it in GitHub Desktop.
Save mals14/eb8acd11f9075dc96b4caaca3c502cc8 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