The Wayback Machine - https://web.archive.org/web/20240703134105/https://www.geeksforgeeks.org/how-to-create-and-download-csv-file-in-javascript/
Open In App

How to create and download CSV file in JavaScript ?

Last Updated : 20 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes we need to fetch the data in the form of a CSV file, it might be user’s details or other data for machine learning or analytics purposes. We can easily fetch the data from any javascript object or JSON file and download it in the form of a CSV file. 

In this article, we will deal with 2 data sources:

  1. Javascript object
  2. JSON object

Data Source: Javascript Object

Approach: In short, we need the header which is referred to by javascript object keys, and rows referred by javascript object values. we need them separated by a comma in order to make it a CSV. We use Blob for building a CSV file.

// Javascript Object
const data = {
id: 1,
name: "Geeks",
profession: "developer"
}

this should be converted to:

id, name, profession
1, Geeks, developer

Step 1: Setting up the project

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">
</head>

<body>
    <button id="action">Download csv</button>

    <script type="text/javascript" 
        src="main.js"></script>
</body>

</html>
main.js
const get = async function () {

    // JavaScript bject
    const data = {
        id: 1,
        name: "Geeks",
        profession: "developer"
    }
}

// Getting element by id and adding eventlistener 
// to listen everytime button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);

Step 2: Creating a csvmaker function in main.js. This function is responsible for making normal java objects in a form of CSV.

main.js
const csvmaker = function (data) {

    // Empty array for storing the values
    csvRows = [];

    // Headers is basically a keys of an object
    // which is id, name, and profession
    const headers = Object.keys(data);

    // As for making csv format, headers must
    // be separated by comma and pushing it
    // into array
    csvRows.push(headers.join(','));

    // Pushing Object values into array
    // with comma separation
    const values = Object.values(data).join(',');
    csvRows.push(values)

    // Returning the array joining with new line 
    return csvRows.join('\n')
}

const get = async function () {

    // JavaScript object
    const data = {
        id: 1,
        name: "Geeks",
        profession: "developer"
    }

    console.log(csvmaker(data));
}

// Getting element by id and adding 
// eventlistener to listen everytime
// button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);

Output:

Step 3: Creating a download function. This function will enable us to download a CSV file containing our passed data.

JavaScript
// Function to download the CSV file
const download = (data) => {
    // Create a Blob with the CSV data and type
    const blob = new Blob([data], { type: 'text/csv' });
    
    // Create a URL for the Blob
    const url = URL.createObjectURL(blob);
    
    // Create an anchor tag for downloading
    const a = document.createElement('a');
    
    // Set the URL and download attribute of the anchor tag
    a.href = url;
    a.download = 'download.csv';
    
    // Trigger the download by clicking the anchor tag
    a.click();
}

// Function to create a CSV string from an object
const csvmaker = (data) => {
    // Get the keys (headers) of the object
    const headers = Object.keys(data);
    
    // Get the values of the object
    const values = Object.values(data);
    
    // Join the headers and values with commas and newlines to create the CSV string
    return [headers.join(','), values.join(',')].join('\n');
}

// Asynchronous function to fetch data and download the CSV file
const get = async () => {
    // Example data object
    const data = {
        id: 1,
        name: "Geeks",
        profession: "developer"
    };
    
    // Create the CSV string from the data
    const csvdata = csvmaker(data);
    
    // Download the CSV file
    download(csvdata);
}

// Add a click event listener to the button with ID 'action'
document.getElementById('action').addEventListener('click', get);

Output:

Data Source: JSON Object

The process is similar for JSON objects

  • We need to make a javascript object mapping through a JSON file. It will work the same as the data we used previously.
JavaScript
// Asynchronous function to fetch and process COVID-19 data
const get = async () => {
    // URL for fetching COVID-19 data
    const url = 'https://data.covid19india.org/data.json';

    // Fetch data from the URL and await the response
    const res = await fetch(url);

    // Extract the 'statewise' array from the JSON response
    const { statewise } = await res.json();

    // Map through the 'statewise' data and create an array of objects
    const data = statewise.map(({ state, statecode, active, confirmed, deaths }) => ({
        state,
        statecode,
        active,
        confirmed,
        deaths
    }));

    // Generate CSV data from the processed data
    const csvdata = csvmaker(data);

    // Download the generated CSV data
    download(csvdata);
}
  • We need to loop over the object values and push them to the array in the csvmaker function in main.js
JavaScript
const csvmaker = function (data) {

    // Empty array for storing the values
    csvRows = [];

    // Headers is basically a keys of an object which 
    // is id, name, and profession
    const headers = Object.keys(data[0]);

    // As for making csv format, headers must be
    // separated by comma and pushing it into array
    csvRows.push(headers.join(','));

    // Pushing Object values into the array with
    // comma separation

    // Looping through the data values and make
    // sure to align values with respect to headers
    for (const row of data) {
        const values = headers.map(e => {
            return row[e]
        })
        csvRows.push(values.join(','))
    }

    // const values = Object.values(data).join(',');
    // csvRows.push(values)

    // returning the array joining with new line 
    return csvRows.join('\n')
}

Output:



Similar Reads

Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to convert a file to zip file and download it using Node.js ?
The Zip files are a common way of storing compressed files and folders. In this article, I'll demonstrate how to convert the file to zip format by using the adm-zip module (NPM PACKAGE). Uses of ADM-ZIP compress the original file and change them to zip format.update/delete the existing files(.zip format). Installation of ADM-ZIP: Step 1: Install th
3 min read
How to create input field that accept CSV file in HTML ?
CSV (Comma Separated Values) is a commonly used file format for storing tabular data. To allow users to upload CSV files to a web application, we can create an input field that accepts CSV files in HTML. There are different approaches to achieve this, ranging from the simple "accept" attribute in the input tag to more advanced third-party libraries
5 min read
How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
How to convert CSV string file to a 2D array of objects using JavaScript ?
A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format. In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript. Given a comma-separated values (CSV) string to a 2D array, using Javascript
4 min read
How to trigger a file download when clicking an HTML button or JavaScript?
In today's digital age, numerous applications offer the feature to upload and download files. For instance, plagiarism checker tools enable users to upload a document file containing text. The tool then checks for plagiarism and generates a report, which can be downloaded by the user. To trigger a file download on a button click we will use a custo
3 min read
How to Download PDF File on Button Click using JavaScript ?
Sometimes, a web page may contain PDF files that can be downloaded by the users for further use. Allowing users to download the PDF files can be accomplished using JavaScript. The below methods can be used to accomplish this task. Table of Content Using html2pdf.js libraryUsing pdfmake LibraryUsing window.print() methodUsing html2pdf.js libraryFirs
5 min read
How to download File Using JavaScript/jQuery ?
The ability to download files directly from a website is an essential feature for many web applications. Whether you're providing documents, images, or other data, enabling users to download files seamlessly enhances their experience and ensures they can access the content offline. This article provides a comprehensive guide on how to implement fil
2 min read
Download Any File From URL with Vanilla JavaScript
Downloading files from a URL using vanilla JavaScript involves creating a link element, setting its href attribute to the file URL, and programmatically triggering a click event. This method allows users to download files without relying on external libraries or frameworks. Downloading files from a URL with vanilla JavaScript is done to enable user
3 min read
How to convert an array to CSV file in PHP ?
To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on fa
2 min read
three90RightbarBannerImg