Welcome folks today in this blog post we will be exporting html table to csv
and download it as attachment inside the browser using blob
object in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> * { 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; } </style> <body> <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> </body> </html> |
As you can see in the above html we are displaying the html table
and then we have the button where we allow the user to export html table to csv
And then we need to add the below javascript
code as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
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"); }); |
As you can see we are first of all converting the html table
to csv
file and downloading it as an attachment using the anchor
element as shown below