Open In App

How to create and download CSV file in JavaScript ?

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




const download = function (data) {
  
    // Creating a Blob for having a csv file format 
    // and passing the data with type
    const blob = new Blob([data], { type: 'text/csv' });
  
    // Creating an object for downloading url
    const url = window.URL.createObjectURL(blob)
  
    // Creating an anchor(a) tag of HTML
    const a = document.createElement('a')
  
    // Passing the blob downloading url 
    a.setAttribute('href', url)
  
    // Setting the anchor tag attribute for downloading
    // and passing the download file name
    a.setAttribute('download', 'download.csv');
  
    // Performing a download with click
    a.click()
}
  
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"
    }
  
    const csvdata = csvmaker(data);
    download(csvdata);
}
  
// Getting element by id and adding
// eventlistener to listen everytime
// button get pressed
const btn = document.getElementById('action');
btn.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




const get = async function () {
  
    // Json Get url 
  
    // Fetching a data in a form of json objects
    const res = await fetch(url);
    const jsonobj = await res.json();
  
    // Getting statewise data (according to json objects)
    const jsondata = jsonobj.statewise
  
    // Making an object and mapping though the data 
    // with keys and values
    const data = jsondata.map(row => ({
        state: row.state,
        statecode: row.statecode,
        active: row.active,
        confirmed: row.confirmed,
        deaths: row.deaths
    }))
  
    // console.log(jsondata)
  
    // console.log(csvmaker(data))
  
    const csvdata = csvmaker(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:



Last Updated : 16 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads