How to export HTML table to CSV using JavaScript ?
Last Updated :
24 Jul, 2024
Comma Separated Values or CSV is a type of text file where each value is delimited by a comma. CSV files are very useful for the import and export of data to other software applications.
Sometimes while developing web applications, you may come into a scenario where you need to download a CSV file converted from an HTML table. In this post, let us discuss how to create this feature using pure JavaScript without using any fancy plugins, modules, or frameworks.
Approach:
Create an HTML table. By using JavaScript and the Document object module (DOM), we are going to extract each column data in a row and combine the data using commas. After doing this to each row, again using DOM, we are going to create a new download link and trigger the link using JavaScript event listeners to download the data to form a CSV file.
Step 1: Create an HTML table: Create a simple HTML page with a table and a button. This button will be used as a trigger to convert the table into comma-separated values and download it in the form of a CSV file. Apply your own needed CSS stylings.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Table to CSV converter</title>
</head>
<body>
<center>
<h1 style="color:green">GeeksForGeeks</h1>
<h2>Table to CSV converter</h2>
<table border="1" cellspacing="0" cellpadding="10">
<tr>
<th>Name</th>
<th>age</th>
<th>place</th>
</tr>
<tr>
<td>Laxman</td>
<td>19</td>
<td>Hyderabad</td>
</tr>
<tr>
<td>Dhoni</td>
<td>22</td>
<td>Ranchi</td>
</tr>
<tr>
<td>Kohli</td>
<td>25</td>
<td>Delhi</td>
</tr>
</table>
<br><br>
<button type="button">download CSV</button>
</center>
</body>
</html>
Step 2: Convert table data into comma-separated values: Write a JavaScript function to retrieve the table data and convert it to comma-separated values. Make use of the document object model to access table data in each column of the rows. This function should be triggered when the user clicks the download button.
JavaScript
function tableToCSV() {
// Variable to store the final csv data
let csv_data = [];
// Get each row data
let rows = document.getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
// Get each column data
let cols = rows[i].querySelectorAll('td,th');
// Stores each csv row data
let csvrow = [];
for (let j = 0; j < cols.length; j++) {
// Get the text data of each cell of
// a row and push it to csvrow
csvrow.push(cols[j].innerHTML);
}
// Combine each column value with comma
csv_data.push(csvrow.join(","));
}
// Combine each row data with new line character
csv_data = csv_data.join('\n');
/* We will use this function later to download
the data in a csv file downloadCSVFile(csv_data);
*/
}
When the tableToCSV() function is triggered, it accesses each table row data using the document object model. The getElementByTagName('tr') retrieves all table row data and stores it in rows variable. The rows[i].querySelectorAll('td,th') will get each column data of that table row. It is then stored in csvrow variable. The csvrow variable data are combined using commas to represent a row of a CSV file and then it is stored in a csv_data variable which represents the data of our CSV file in combination. We then join csv_data values using the newline character as each row in a CSV file is represented in a new line. Now our data is ready to be exported into a CSV file.
Step 3: Write a script to download the CSV file: Now that we have our converted data ready, we need to write a script to create a CSV file, feed our data into it, and trigger the browser to download it automatically after the user has clicked the download button. Since this function will be triggered after the table data is converted, we will call this function inside tableToCSV() function.
JavaScript
function downloadCSVFile(csv_data) {
// Create CSV file object and feed our
// csv_data into it
CSVFile = new Blob([csv_data], { type: "text/csv" });
// Create to temporary link to initiate
// download process
let temp_link = document.createElement('a');
// Download csv file
temp_link.download = "GfG.csv";
let url = window.URL.createObjectURL(CSVFile);
temp_link.href = url;
// This link should not be displayed
temp_link.style.display = "none";
document.body.appendChild(temp_link);
// Automatically click the link to trigger download
temp_link.click();
document.body.removeChild(temp_link);
}
This function will take the CSV data that was formed earlier, as the argument. We will create a new file by creating a blob object of type CSV and then feed our CSV data into it. We need a link to trigger the browser window to download the file. However, we don't have any link in our HTML to do so. So, we will create a new link using DOM and provide its attributes with the appropriate values. This link so created should not be visible to the user as this link is solely for download triggering purposes and not for any other. So we need to make sure that this link is not visible to the user and is removed once the download triggering process is over. Again we can use DOM to meet all our requirements.
Using click() event listener, we can automatically let the link be clicked and download our CSV file. Now our CSV file should be successfully downloaded.
Final Code
HTML
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style="color:green">GeeksForGeeks</h1>
<h2>Table to CSV converter</h2>
<table border="1" cellspacing="0" cellpadding="10">
<tr>
<th>Name</th>
<th>age</th>
<th>place</th>
</tr>
<tr>
<td>Laxman</td>
<td>19</td>
<td>Hyderabad</td>
</tr>
<tr>
<td>Dhoni</td>
<td>22</td>
<td>Ranchi</td>
</tr>
<tr>
<td>Kohli</td>
<td>25</td>
<td>Delhi</td>
</tr>
</table>
<br><br>
<button type="button" onclick="tableToCSV()">
download CSV
</button>
</center>
<script type="text/javascript">
function tableToCSV() {
// Variable to store the final csv data
let csv_data = [];
// Get each row data
let rows = document.getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
// Get each column data
let cols = rows[i].querySelectorAll('td,th');
// Stores each csv row data
let csvrow = [];
for (let j = 0; j < cols.length; j++) {
// Get the text data of each cell
// of a row and push it to csvrow
csvrow.push(cols[j].innerHTML);
}
// Combine each column value with comma
csv_data.push(csvrow.join(","));
}
// Combine each row data with new line character
csv_data = csv_data.join('\n');
// Call this function to download csv file
downloadCSVFile(csv_data);
}
function downloadCSVFile(csv_data) {
// Create CSV file object and feed
// our csv_data into it
CSVFile = new Blob([csv_data], {
type: "text/csv"
});
// Create to temporary link to initiate
// download process
let temp_link = document.createElement('a');
// Download csv file
temp_link.download = "GfG.csv";
let url = window.URL.createObjectURL(CSVFile);
temp_link.href = url;
// This link should not be displayed
temp_link.style.display = "none";
document.body.appendChild(temp_link);
// Automatically click the link to
// trigger download
temp_link.click();
document.body.removeChild(temp_link);
}
</script>
</body>
</html>
Output:
Conclusion:
In conclusion,developers can leverage pure JavaScript that allows them to convert HTML table data into CSV format and enable effortless downloads, making data interchange between web applications easier and much efficient. By utilizing DOM manipulation and event handling, this method cutshorts the need for external plugins or frameworks, ensuring lightweight and versatile implementation. This approach not only enhances the flexibility of web development but also empowers developers with a fundamental technique for data management and integration across various web platforms.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
HTML Tutorial HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
11 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Sliding Window Technique Sliding Window Technique is a method used to solve problems that involve subarray or substring or window. The main idea is to use the results of previous window to do computations for the next window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding t
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Example of an AVL Tree:The balance factors for different nodes are : 12 :1, 8:1, 18:1, 5:1, 11:0, 17:0 and 4:0. Since all differences
4 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read