-
-
Save mals14/eb8acd11f9075dc96b4caaca3c502cc8 to your computer and use it in GitHub Desktop.
Create CSV on frontend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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