Open In App

How to create and download CSV file in JavaScript ?

Last Updated : 16 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

CSV (Comma-Separated Values) files are widely used for data transfer, analytics, and storage purposes. They allow you to easily fetch data from JavaScript or JSON objects and save it in a readable format for users, machine learning, or analytics tasks. In this article, we’ll explore how to convert data from JavaScript objects and JSON objects into CSV files and download them using JavaScript.

Why Convert Data to CSV?

  • Data Analysis: CSV files are easy to import into data analysis tools like Excel, Google Sheets, or Python for further processing.
  • Machine Learning: CSV is a common format for training data used in machine learning models.
  • Data Export: Allow users to download data in a simple, accessible format.

Data Sources Covered

  1. JavaScript Object
  2. JSON Object

Let’s look at how to handle each of these data sources.

Data Source 1: JavaScript Object

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 2: JSON Object

The process is similar for JSON objects

  • The process for JSON objects is similar to JavaScript objects. You need to map the JSON object to a JavaScript object structure and then apply the same CSV conversion and download logic.
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:

By using these simple JavaScript functions, you can easily convert JavaScript objects and JSON data into CSV format and download them. This technique is especially useful for exporting data, handling analytics, and integrating data processing workflows in web applications.



Next Article

Similar Reads