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
How to Convert HTML Table to JSON in JavaScript?
HTML tables are commonly used to present structured data on websites. In many scenarios, this tabular data needs to be converted to JSON format for processing, storage, or server communication. We will discuss different approaches to converting HTML tables to JSON using JavaScript. These are the fol
3 min read
How to make HTML table expand on click using JavaScript ?
The expandable table can be achieved by using JavaScript with HTML. By Clicking on a row of the table, it expands and a sub-table pops up. When the user again clicks on that row the content will hide. This can be very useful when the data is complex but it is inter-related. Example 1: The following
5 min read
How to convert JSON data to a html table using JavaScript/jQuery ?
To convert JSON data into an HTML table, there are multiple approaches, each of which has its own strengths. Let's walk through both approaches you mentioned, detailing how each one works. Table of Content Using for loopUsing JSON.stringify() MethodApproach 1: Using for loopTake the JSON Object in a
4 min read
How to Remove Column from HTML Table using JavaScript ?
Given an HTML table and the task is to remove the certain column from the HTML table. There are two approaches that are discussed below: Approach 1: First, select the table and also get the rows of table using table.rows. Get the number of columns of a row and go through each one of the columns. Use
3 min read
How to hide the table header using JavaScript ?
In this article, we will see the methods to hide the table header using JavaScript. There are two approaches that can help to hide a table header with the help of JavaScript. They are discussed below: Using style and display propertyUsing jQuery hide Method Approach 1: Select the header using a CSS
2 min read
How to Convert HTML to JSON in JavaScript ?
Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript. Below are the approaches to convert html to JSON in JavaScript: Table of Content Using html-to-json Lib
2 min read
How to Access <tr> element from Table using JavaScript ?
Given an HTML table and the task is to access the table element from the Controller and highlight any row that we want. Approach: We will use a basic DOM operation in JavaScript to access table row element. We will be adding highlight class to the row that we click, if the highlight class is already
2 min read
How to Append Header to a HTML Table in JavaScript ?
JavaScript allows us to dynamically modify the structure of a table based on user interaction or other dynamic events. Here we will use JavaScript to dynamically create a Header row and then append it to the HTML table. ApproachIn this approach, we are using create elements along with DOM manipulati
3 min read
How to Create Time-Table Schedule using HTML?
A time table or schedule is essential for organizing tasks, events, or classes. Weâll create a basic time-table layout using HTML. A Table is an arrangement of rows and columns. Anyone can create a table by knowing the basics of HTML(HyperText Markup Language). In HTML we can use the <table> t
3 min read
How to Convert HTML Form Field Values to JSON Object using JavaScript?
Storing HTML input data into JSON format using JavaScript can be useful in various web development scenarios such as form submissions, data processing, and AJAX requests. Here we will explore how to convert the HTML form input data into the JSON format using JavaScript. ApproachThe HTML file contain
2 min read