How to Create a CSV file in JavaScript

← Prev

This tutorial shows how to create a CSV file using JavaScript and download it directly from the browser. CSV (Comma Separated Values) is a popular file format for storing and exchanging structured data. If you're looking for a simple way to export data to CSV using JavaScript, this example will help you get started quickly.

What is CSV?

CSV stands for Comma-Separated Values, a simple method for representing tabular data as plain text. In a CSV format, each row of data is written on a new line, and individual values within a row are separated by commas.

CSV is widely used for storing, transferring, and exchanging structured data between different systems and applications because it is lightweight, easy to read, and supported by almost every spreadsheet, database, and programming language.

A typical CSV looks like this:

Name,Email,Age
Arun Banik,arun@example.com,47
Shouvik B,shouvik@example.com,16
Mike T,mike@example.com,25

The first row contains column headers, and each subsequent row represents a record. Each value is seperated by a comma.

Why CSV is used?

CSV is popular because it is simple. It works in EXCEL, Google Sheets, and databases. Most importantly (from a a programmers point of view), it's easy for programs to and generate. It dosn't require special software.

Example:

 <script>
    const csv = `ID,Name
     1,Alpha
     2,Bravo`;

    const blob = new Blob([csv], { type: "text/csv" });

    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "sample.csv";
    a.click();

    URL.revokeObjectURL(a.href);
</script>
Try it

This script creates a CSV file in memory and automatically downloads it to the user's computer.

Here's what the script does.

1. Declare variable and add data

This is the string containing the CSV data.

const csv = `ID,Name
1,Arun
2,Shouvik`;

There a three rows. The first row represents the header, ID and Name. The remaining two rows (2nd and 3rd) are data.

The content looks like this:

ID,Name
1,Arun
2,Shouvik

2) Create a BLOB

const blob = new Blob([csv], { type: "text/csv" });

In JavaScript, a BLOB is an object that holds raw data, such as, text, image, or files. The browser now has a file like object containing the CSV data.

3. Create an invisible link

const a = document.createElement("a");

The above script creates an HTML <a> (anchor/link) element. This is equivalent to <a></a>. But it exists only in JavaScript and doesn't need to be added to the page.

4. Generate a temporary file URL

a.href = URL.createObjectURL(blob);

URL.createObjectURL(blob) creates a temporary URL that points to the Blob.

5. Set the download filename

a.download = "sample.csv";

The download attribute tells the browser... when this link is clicked, download the file instead of opening it. Simple.

👉 Now convert the CSV into an HTML table.

← Previous