Home > Web Front-end > JS Tutorial > How to create and download CSV files in JavaScript?

How to create and download CSV files in JavaScript?

王林
Release: 2023-09-17 08:09:03
forward
812 people have browsed it

如何在 JavaScript 中创建和下载 CSV 文件?

JavaScript has powerful capabilities to manipulate various data and handle files in different formats. Sometimes, developers need to process data using CSV files while developing web applications using JavaScript.

For example, we are building an e-commerce platform where users can buy and sell products. Additionally, we want to allow users to download order details into a CSV file based on a time range. In this case, we need to interact with the data and the CSV file. Another example is that online banking websites allow us to download transaction details in a CSV file.

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

grammar

Users can create and download CSV files from given data by following the following syntax.

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

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

In the above syntax, "csvData" is an array appending the CSV file rows with data. After that, we create a CSV file from csvData using anchor tags and download the file by clicking on the anchor element.

Example

In the following example, we first create an 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 comma separated object keys to the "csvData" variable. After that, we loop through the given array of objects and prepare a single row by concatenating each attribute value in the same order (separated by commas and appending it to the "CSVData" variable).

Next, we create the anchor element using the createElement() method and add "csvData" as the value of the href attribute after encoding using the encodeURI() method. Additionally, we set the target value and download attribute value. Finally, we click on the anchor element to download the CSV file.

In the output, the user can click a button to download the data to a 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>
Copy after login

Example

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

Programmers can follow the following steps to understand the sample code -

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

Step 2 - After that, convert the response into a JSON object using the res.json() method.

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

Step 4 - Get the first object from the response and pass it as argument to the Object.keys() method to get all the keys in the array. After that, use the join() method to concatenate the keys into a single string, separated by commas and push to the csvData array.

Step 5 - Loop through all the objects we got in the response. In the loop, we use the map() method with the 'heads' array to get the value from the current object based on the 'heads' array element (object key) and map the value to the 'rowValues' array.

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

Step 7 - Concatenate all the elements of the "csvData" array using the "

" delimiter and pass it as getCSVFile() function parameter.

Step 8 - In the getCSVFile() function, create a new instance of the anchor element. After that, set the encoded csvData to the 'href' attribute value and set the 'target' and 'download' attribute values.

Step 9- Click on 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>
Copy after login

Both sample codes contain two main parts. The first part is to manipulate the given data and concatenate them with a comma separated string, which we will use for the CSV file data. The next part is to append the data to the file and download the file. To create a CSV file, we use a dummy instance of the anchor element.

The above is the detailed content of How to create and download CSV files in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template