Skip to content

Instantly share code, notes, and snippets.

@asruldev
Created December 22, 2020 11:00
Show Gist options
  • Save asruldev/3b058a6ec8182165cbfe58da144813df to your computer and use it in GitHub Desktop.
Save asruldev/3b058a6ec8182165cbfe58da144813df to your computer and use it in GitHub Desktop.
Export to EXcell from JS
function fnExcelReport() {
var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
tab_text = tab_text + '<x:Name>Test Sheet</x:Name>';
tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
tab_text = tab_text + "<table border='1px'>";
tab_text = tab_text + $('#myTable').html();
tab_text = tab_text + '</table></body></html>';
var data_type = 'data:application/vnd.ms-excel';
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
if (window.navigator.msSaveBlob) {
var blob = new Blob([tab_text], {
type: "application/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, 'Test file.xls');
}
} else {
$('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
$('#test').attr('download', 'Test file.xls');
}
}
<a href="#" id="test" onClick="javascript:fnExcelReport();">download</a>
<table id="myTable">
<thead>
<tr>
<td style="background: red"><b>Name</b>
</td>
<td style="background: pink"><b>Age</b>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Tester1</td>
<td>30</td>
</tr>
<tr>
<td>Tester2</td>
<td>29</td>
</tr>
<tr>
<td>Tester3</td>
<td>17</td>
</tr>
</tbody>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment