reply View all Tutorials & Projects

The Easiest Way to Export to CSV File in JavaScript

In this video I'll be showing you one of the easiest ways to export some JavaScript data (e.g. arrays or objects) into CSV or even a downloadable file.

Video Tutorial

Source Code

You can find the source code for this video below.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>The Easiest Way to Generate CSV in JavaScript</title>
</head>
<body>
	<button type="button" id="btnDownloadCsv">Download CSV</button>

	<script src="https://cdn.jsdelivr.net/npm/json2csv"></script>
	<script>
		const data = [
			{
				id: "de86e2",
				username: "dcode",
				age: 36
			},
			{
				id: "aa11b4",
				username: "code.slayer1",
				age: 24
			},
			{
				id: "be45dd",
				username: "javascriptking",
				age: 42
			}
		];

		const btnDownloadCsv = document.getElementById("btnDownloadCsv");

		btnDownloadCsv.addEventListener("click", () => {
			downloadCsv("dcode-test.csv", json2csv.parse(data));
		});

		function downloadCsv(filename, csvData) {
			const element = document.createElement("a");

			element.setAttribute("href", `data:text/csv;charset=utf-8,${csvData}`);
			element.setAttribute("download", filename);
			element.style.display = "none";

			document.body.appendChild(element);
			element.click();
			document.body.removeChild(element);
		}
	</script>
</body>
</html>

If you have any questions about this code, please leave a comment on the video.