Code mẫu

Link: https://bobbyhadz.com/blog/javascript-export-table-to-excel

The easiest way to export an HTML table to Excel in JavaScript is to use the popular SheetJS library.

The SheetJS module can be used to read the HTML table and extract its data into an Excel file.

Here is the HTML for the example.

index.html


 

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } table { border-collapse: collapse; } table td, table th { border: 1px solid black; } </style> <script src="https://cdn.sheetjs.com/xlsx-0.19.3/package/dist/xlsx.full.min.js"></script> </head> <body> <h2>bobbyhadz.com</h2> <table id="my-table"> <thead> <tr> <th>Employee</th> <th>Salary</th> <th>Country</th> </tr> </thead> <tbody> <tr> <td>Alice</td> <td>Bobby Hadz</td> <td>Carl</td> </tr> <tr> <td>1500</td> <td>1400</td> <td>2000</td> </tr> <tr> <td>Austria</td> <td>Belgium</td> <td>Canada</td> </tr> </tbody> </table> <br /> <br /> <button id="btn-export"><b>Export as XLSX</b></button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js


 

const exportButton = document.getElementById('btn-export'); const table = document.getElementById('my-table'); exportButton.addEventListener('click', () => { /* Create worksheet from HTML DOM TABLE */ const wb = XLSX.utils.table_to_book(table, {sheet: 'sheet-1'}); /* Export to file (start a download) */ XLSX.writeFile(wb, 'MyTable.xlsx'); });

Download template