Skip to content
Related Articles

Related Articles

How to create and download CSV file in JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 10 Mar, 2022

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, Geeks, profession
1, Geeks, developer

Step 1: Setting up the project

index.html

  

<
main.js

  

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

 

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
// eventlistner 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 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
// eventlistner to listen everytime
// button get pressed
const btn = document.getElementById('action');
btn.addEventListener('click', get);


Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!