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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Export HTML Table to Excel</title> <script src="https://cdn.jsdelivr.net/npm/exceljs/dist/exceljs.min.js"></script> </head> <body> <h2>HTML Table to Excel Export Example</h2> <!-- Sample Table --> <table id="data-table" border="1"> <thead> <tr> <th>Product</th> <th>Price</th> <th>Quantity</th> </tr> </thead> <tbody> <tr> <td>Apple</td> <td>$1.00</td> <td>10</td> </tr> <tr> <td>Banana</td> <td>$0.50</td> <td>20</td> </tr> <tr> <td>Orange</td> <td>$1.20</td> <td>15</td> </tr> </tbody> </table> <!-- Export Button --> <button id="export-btn">Export to Excel</button> <script> // Wait for the DOM to be fully loaded document.addEventListener('DOMContentLoaded', function () { // Get the export button const exportButton = document.getElementById('export-btn'); const table = document.getElementById('data-table'); // Function to convert table to Excel file and download exportButton.addEventListener('click', async function () { // Create a new workbook const wb = new ExcelJS.Workbook(); const ws = wb.addWorksheet('Sheet 1'); // Get the headers from the table const headers = []; const rows = []; const headerCells = table.querySelectorAll('thead th'); headerCells.forEach(cell => { headers.push(cell.innerText); }); // Add headers to worksheet ws.addRow(headers); // Get table rows const tableRows = table.querySelectorAll('tbody tr'); tableRows.forEach(row => { const rowData = []; const cells = row.querySelectorAll('td'); cells.forEach(cell => { rowData.push(cell.innerText); }); rows.push(rowData); }); // Add data rows to worksheet rows.forEach(rowData => { ws.addRow(rowData); }); // Set column widths based on the header length ws.columns = headers.map(header => ({ width: header.length + 5 })); // Generate an Excel file as a buffer const buffer = await wb.xlsx.writeBuffer(); // Create a Blob from the buffer const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); // Create a link element to trigger the download const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = 'exported_table.xlsx'; // Set the file name // Programmatically click the link to trigger the download link.click(); }); }); </script> </body> </html> |