JSFiddle - React, Tailwind, and code Playground
by ndncll
HTML
<html>
<head>
</head>
<body>
<h2>Nidhin Chalil nDn</h2>
<p>HTML to excel export</p>
<table id='testExportId'>
<tr>
<th bgcolor='red'>Firstname</th>
<th bgcolor='red'>Lastname</th>
<th bgcolor='red'>Savings</th>
</tr>
<tr>
<td>Peter</td>
<td>Griffin</td>
<td>$100</td>
</tr>
<tr>
<td>Lois</td>
<td>Griffin</td>
<td>$150</td>
</tr>
<tr>
<td>Joe</td>
<td>Swanson</td>
<td>$300</td>
</tr>
<tr>
<td>Cleveland</td>
<td>Brown</td>
<td>$250</td>
</tr>
</table>
<br>
<button id='btnExport'>
Export To Excel
</button>
</body>
</html>
CSS
table, td, th {
border: 1px solid black;
}
table {
border-collapse: collapse;
width: 100%;
}
th {
text-align: left;
}
JavaScript
$(document).ready(function(){
$("#btnExport").click(
function () {
tableToExcel('testExportId','test','TestExport');
}
);
})
function getIEVersion()
// Returns the version of Windows Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
function tableToExcel(table, sheetName, fileName) {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
return fnExcelReport(table, fileName);
}
var uri = 'data:application/vnd.ms-excel;base64,',
templateData = '<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><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>',
base64Conversion = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
formatExcelData = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
$("tbody > tr[data-level='0']").show();
if (!table.nodeType)
table = document.getElementById(table)
var ctx = { worksheet: sheetName || 'Worksheet', table: table.innerHTML }
var element = document.createElement('a');
element.setAttribute('href',...