This JavaScript code example helps you export the HTML table to Excel. It selects and exports table content. It helps convert tables to Excel.
You can use this code on any webpage with an HTML table. It helps users export table data into Excel format easily. Enhances user experience by simplifying data management.
How to Export HTML Table to Excel Using JavaScript
1. First, load the following Bootstrap CDN link into the head tag of your HTML document.
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css'>
2. Ensure you have an HTML table on your webpage that contains the data you want to export. You can structure your table however you like, with headers and rows.
<div class="container my-5"> <button class="btn btn-primary" id="btn">Export to Excel</button> <table id="Record" class="table table-striped table-dark my-3"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> <tr> <th scope="row">4</th> <td>Larry</td> <td>the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div>
3. Load the following Table2Excel CDN link before closing the body tag.
<script src='https://cdn.jsdelivr.net/npm/table2excel@1.0.4/dist/table2excel.min.js'></script>
4. Add the following JavaScript code to your webpage. This code sets up an event listener on a button, which, when clicked, triggers the export of the HTML table data to Excel format.
document.getElementById("btn").addEventListener("click", () => { let table2excel = new Table2Excel(); table2excel.export(document.querySelector("#Record")); });
You can further enhance this functionality by adding error handling, additional export options, or integrating it with server-side scripts for more complex data manipulation before export.
Congratulations! You’ve successfully implemented a JavaScript solution to export HTML table data to Excel, enhancing the usability and accessibility of your web application