I\'ve been looking into some jQuery plugins that are capable of doing this. I decided to use the one at http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreads
This is the code you can use to export HTML table to excel file with custom file name. I tried on IE11 , Firefox 48 & chrome 51 .
- Add
in the HTML part .
- Add a button
, which will call the function "toExcel_()" .
Ps: I'm new to Stackoverflow , So please excuse my format of answering :D
function toExcel_(){
var tab_text="";
var textRange; var j=0;
tab = document.getElementById('tblExport'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+" ";
//tab_text=tab_text+"";
}
tab_text=tab_text+"
";
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Report.xls");
}
else // For Chrome and firefox (Other broswers not tested)
{
uriContent = "data:application/vnd.ms-excel," + encodeURIComponent(tab_text);
var sa = document.createElement("a");
sa.setAttribute("href", uriContent);
sa.setAttribute("download", "Report"+postfix +".xls");
document.body.appendChild(sa); // Required for FF
sa.click();
}
return (sa);
}