Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
- <html>
- <body>
- <table>
- <tr>
- <th>Name</th>
- <th>Email</th>
- <th>Country</th>
- </tr>
- <tr>
- <td>John Doe</td>
- <td>john@gmail.com</td>
- <td>USA</td>
- </tr>
- <tr>
- <td>Stephen Thomas</td>
- <td>stephen@gmail.com</td>
- <td>UK</td>
- </tr>
- <tr>
- <td>Natly Oath</td>
- <td>natly@gmail.com</td>
- <td>France</td>
- </tr>
- </table>
- <button onclick="exportTableToCSV('members.csv')">Export HTML Table To CSV File</button>
- <script>
- function downloadCSV(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;
- // Create a link to the file
- downloadLink.href = window.URL.createObjectURL(csvFile);
- // Hide download link
- downloadLink.style.display = "none";
- // Add the link to DOM
- document.body.appendChild(downloadLink);
- // Click download link
- downloadLink.click();// throwing error.
- }
- function exportTableToCSV(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 file
- downloadCSV(csv.join("n"), filename);
- }
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment