search
HomeWeb Front-endJS TutorialHow to create and download CSV files in JavaScript?

如何在 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();

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 id="Creating-and-dowlonading-the-CSV-file-from-the-given-data-in-JavaScript">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 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 id="Creating-and-dowlonading-the-CSV-file-i-after-fetching-JSON-data-in-JavaScript">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 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!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor