Client-Side HTML Table to Excel Export Using Base64 Data URIs
A lightweight method for generating Excel-compatible files directly from HTML tables utilizes Base64-encoded data URIs with Microsoft Office XML namespaces. This approach requires no server-side processing or external dependnecies.
HTML Structure
<button id="downloadTrigger">Export to Excel</button>
<table id="sourceData">
<thead>
<tr>
<th>Product</th>
<th>Revenue</th>
</tr>
</thead>
<tbody>
<tr>
<td>Widget A</td>
<td>12500</td>
</tr>
</tbody>
</table>
Core Implementation
The solution constructs a valid Excel document by wrapping table markup within Office-specific XML schemas, then encoding the result as a downloadable payload:
const exportTableToExcel = (tableIdentifier, worksheetName = 'Sheet1') => {
const mimeHeader = 'data:application/vnd.ms-excel;base64,';
const documentTemplate = `<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
<head>
<meta charset="UTF-8">
<!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>${worksheetName}</x:Name>
<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>${document.getElementById(tableIdentifier).outerHTML}</body>
</html>`;
const binaryToAscii = (content) => window.btoa(unescape(encodeURIComponent(content)));
return mimeHeader + binaryToAscii(documentTemplate);
};
Trigger Mechanisms
For anchor elements, bind the generated URI directly to the href attribute:
document.querySelector('#exportLink').addEventListener('click', function() {
this.href = exportTableToExcel('sourceData', 'SalesReport');
this.download = 'financial_data.xls';
});
For button elements or programmatic triggers lacking native download capabilities, instantiate a temporary anchor node to handle the binary stream:
document.getElementById('downloadTrigger').addEventListener('click', () => {
const dataUri = exportTableToExcel('sourceData');
const tempAnchor = document.createElement('a');
tempAnchor.href = dataUri;
tempAnchor.download = 'export.xls';
tempAnchor.style.display = 'none';
document.body.appendChild(tempAnchor);
tempAnchor.click();
document.body.removeChild(tempAnchor);
});
Technical Constraints
Direct assignment to window.location.href fails when handling Base64-encoded data URIs in modern browsers due to security policies restricting navigation to non-HTTP schemes. The temporary anchor element approach circumvents this limitation by leveraging the HTML5 download attribute within the same-origin context, preserving the filename specification capability that window.location lacks.