This JavaScript code snippet helps you to create a functionality to export an HTML table to CSV file. It enables the user to export the data from an HTML table as a CSV file when a button is clicked. The export_table_to_csv
function retrieves the data from the HTML table, converts it into CSV format, and calls the download_csv
function to download the file.
The download_csv
function creates a Blob object from the CSV data, creates a download link with the filename provided, adds it to the DOM, and triggers a click event to initiate the download. Overall, this code provides a convenient way to export tabular data from a webpage as a CSV file.
How to Create JavaScript Export Table to CSV Feature
Create the HTML table and place your data inside it as follows:
<table> <tr><th>Name</th><th>Age</th><th>Country</th></tr> <tr><td>Geronimo</td><td>26</td><td>France</td></tr> <tr><td>Natalia</td><td>19</td><td>Spain</td></tr> <tr><td>Silvia</td><td>32</td><td>Russia</td></tr> </table> <button>Export HTML table to CSV file</button>
Style the table using the following CSS styles. These basic CSS rules are optional, you can style the table according to your needs.
* { color: #2b2b2b; font-family: "Roboto Condensed"; } th { text-align: left; color: #4679bd; } tbody > tr:nth-of-type(even) { background-color: #daeaff; } button { cursor: pointer; margin-top: 1rem; }
Finally, add the following JavaScript function to your project to enable the export feature.
function download_csv(csv, filename) { var csvFile; var downloadLink; // CSV FILE csvFile = new Blob([csv], {type: "text/csv"}); // Download link downloadLink = document.createElement("a"); // File name downloadLink.download = filename; // We have to create a link to the file downloadLink.href = window.URL.createObjectURL(csvFile); // Make sure that the link is not displayed downloadLink.style.display = "none"; // Add the link to your DOM document.body.appendChild(downloadLink); // Lanzamos downloadLink.click(); } function export_table_to_csv(html, filename) { var csv = []; var rows = document.querySelectorAll("table tr"); for (var i = 0; i < rows.length; i++) { var row = [], cols = rows[i].querySelectorAll("td, th"); for (var j = 0; j < cols.length; j++) row.push(cols[j].innerText); csv.push(row.join(",")); } // Download CSV download_csv(csv.join("\n"), filename); } document.querySelector("button").addEventListener("click", function () { var html = document.querySelector("table").outerHTML; export_table_to_csv(html, "table.csv"); });
That’s all! hopefully, you have successfully created functionality for exporting the HTML tables to CSV files using this JavaScript code. If you have any questions or suggestions, feel free to comment below.