How to create and download CSV file in JavaScript?


JavaScript has great capability to manipulate various data and handle them with files of different formats. Sometimes, developers require to handle the data with the CSV file while developing web applications using JavaScript.

For example, we are building an e-commerce platform where users can buy and sell products. Also, we want to allow users to download their order details according to the time horizon into the CSV file. We need to interact with the data and CSV files in such cases. Another example is online banking sites allow us to download the transaction details in CSV files.

In this tutorial, we will learn to create the csv file from the given data in the JavaScript or JSON object format and download the file.

Syntax

Users can follow the syntax below to create and download the CSV file from the given data.

laptops.forEach(function (row) {
   csvData += data
});

let anchor = document.createElement('a');
anchor.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvData);
anchor.click();

In the above syntax, ‘csvData’ is an array that appends the CSV file rows using the data. After that, we use the anchor tag to create the CSV file from the csvData and download the file by clicking the anchor element.

Example

In the example below, we first created the array of objects named ‘laptops’, where each object of the array contains the brand, processor, price, and RAM properties.

In the downloadFile() function, we add the object keys with commas seprated to the ‘csvData’ variable. After that, we traverse the given array of objects and prepare a single row by joining each property value in the same order by separating the comma and appending it to the ‘CSVData’ variable.

Next, we create the anchor element using the createElement() method and add the ‘csvData’ as a value of the href attribute after encoding using the encodeURI() method. Also, we set the value of the target and download attribute value. At last, we click the anchor element to download the CSV file.

In the output, users can click the button to download the data into the CSV file.

<html>
<body>
   <h3>Creating and dowlonading the CSV file from the given data in JavaScript</h3>
   <div id="data"> </div>
   <button onclick="downloadFile()"> Download CSV file </button>
   <script>
      let laptops = [{
         brand: 'HP',
         processor: 'i3',
         price: 30000,
         ram: 4
      },
      {
         brand: 'Dell',
         processor: 'i5',
         price: 50000,
         ram: 8
      },
      {
         brand: 'Apple',
         processor: 'i7',
         price: 70000,
         ram: 16
      },
      {
         brand: 'Lenovo',
         processor: 'i3',
         price: 35000,
         ram: 4
      },
      {
         brand: 'Asus',
         processor: 'i5',
         price: 45000,
         ram: 8
      },
      {
         brand: 'Acer',
         processor: 'i7',
         price: 65000,
         ram: 16
      }
      ];
   
      // Function to download data to a CSV file
      function downloadFile() {
      
         // Add header
         let csvData = 'Brand, Processor, Price, RAM
'; // Add data laptops.forEach(function (row) { csvData += row.brand + ',' + row.processor + ',' + row.price + ',' + row.ram + '
'; }); // Download the CSV file let anchor = document.createElement('a'); anchor.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvData); anchor.target = '_blank'; anchor.download = 'laptops.csv'; anchor.click(); } </script> </body> </html>

Example

In the example below, we will fetch the data from the API and use the JSON data to create a CSV file. We created the button in the HTML part, and when the user clicks the button, it executes the downloadFile() function to fetch the JSON data and download it into the CSV file.

Programmers can follow the steps below to understand the example code −

Step 1 − Use the fetch() API to fetch the data from the API URL.

Step 2 − After that, use the res.json() method to convert the response into the JSON object.

Step 3 − In the then() block, initialize the csvData[] array to store the rows of the CSV file.

Step 4 − Take the first object from the response and pass it as a parameter of the Object.keys() method to get all keys in the array. After that, use the join() method to join the keys in a single string with comma separated and push to the csvData array.

Step 5 − Traverse all objects which we got in the response. In the loop, we use the map() method with the ‘heads’ array to get the values from the current object according to the ‘heads’ array elements (object keys) and map values to the ‘rowValues’ array.

Step 6 − Next, use the join() method to join all elements of the ‘rowValues’ array and push them into the ‘csvData’ array.

Step 7 − Join all elements of the ‘csvData’ array with a ‘
’ delimiter and pass it as a getCSVFile() function parameter.

Step 8 − In the getCSVFile() function, create a new instance of the anchor element. After that, set the csvData as a ‘href’ attribute value after encoding, and set the ‘target’ and ‘download’ attribute values.

Step 9 − Click the anchor element to download the file.

<html>
<body>
   <h3>Creating and dowlonading the CSV file </i> after fetching JSON data in JavaScript</h3>
   <div id = "data"> </div>
   <button onclick = "downloadFile()"> Download CSV file </button>
   <script>
      function downloadFile() {
         let APIURL = "https://dummyjson.com/products";
         
         // Fetch data from API
         fetch(APIURL)
         .then(response => response.json())
         .then(data => {
            let csvData = [];
            
            // Get headers
            let heads = Object.keys(data.products[0]);
            
            // Add headers to csvData
            csvData.push(heads.join(','));
            
            // Traveres through each row
            for (let row of data.products) {
               
               // Get values from each row
               let rowValues = heads.map(headerData => {
                  
                  // Get value according to the header
                  let final = ('' + row[headerData]).replace(/"/g, '"');
                  return `"${final}"`;
               });
               
               // Push values in csvData
               csvData.push(rowValues.join(','));
            }
            // Call function to download CSV file
            getCSVFile(csvData.join('
')); }); } function getCSVFile(csvData) { let anchor = document.createElement('a'); anchor.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvData); anchor.target = '_blank'; anchor.download = 'test.csv'; anchor.click(); } </script> </body> </html>

Both example code contains two main parts. The first part is manipulating the given data and joining them with comma seprated string, which we use for the CSV file data. The next part is to append data to the file and download the file. For creating the CSV file, we use the virtual instance of the anchor element.

Updated on: 14-Jul-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements