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
Here is the best way you can do. You can specify the file name too for downloading. Just pass tableid, sheet name, file name to the function below, it will download. See fiddle for downloading in IE too.
https://jsfiddle.net/ndncll/ehnbxo1u/
function tableToExcel(table, sheetName, fileName) {
fileName = fileName + new Date().formatDateTime('MM_DD_YYYY', 'HH_mm_ss');
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', 'data:application/vnd.ms-excel;base64,' + base64Conversion(formatExcelData(templateData, ctx)));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);}
As @charlietfl said you need the .click()
binding inside the $(document).ready
because if not the element doesn't exist when you try to bind it.
And this way you dont need to use a plugin
function exportGrid(gridID,filename) {
var html = $('#' + gridID).html();
var a = document.createElement('a');
a.id = 'tempLink';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename + ".xls";
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('tempLink').remove();
}
$(document).ready(function() {
$("button").click(function(){
exportGrid("TheGridId","The excel name");
});
});
Here you have a example https://jsfiddle.net/0mzn7uLq/
VERY IMPORTANT, make sure the columns and rows have width greater than 0, this becomes an issue especially when rows are moved from one table to another table, (I have faced it when I moved rows between two dataTables)
if columns(th) or rows(td) width is 0, you will get the table downloaded as .xls file, but the columns gets hidden in the excel file,
use css or jquery to set the width greater than 0
css
<your table> th, <your table> td {
width:<your preference>px;
}
jquery
$("<your table> th").css("width","<your preference>px");
$("<your table> td").css("width","<your preference>px");
$("<add button>").click(function(e) {
var a = document.createElement('a');
var dataType = 'data:application/vnd.ms-excel';
var getTable = document.getElementById('<add table id>');
var readTable = getTable.outerHTML.replace(/ /g, '%20');
a.href = dataType + ', ' + readTable;
a.download = '<filename>.xls';
a.click();
e.preventDefault();
});
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
<iframe id="txtArea1" style="display:none"></iframe>
in the HTML part .- Add a button
<button id="btnExport" onclick="toExcel_()">Export to excel</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="<table border='2px'><tr bgcolor='#87AFC6'>";
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+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
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);
}
Managed to fix it. I initially suspected that not putting it inside the ready function would be a problem and thought it would fix the issue, but that was only part of the problem. I also forgot a comma. The finished result is as follows.
<script>
$(document).ready(function() {
//activate footable jquery plugin (this is the dynamic table on the report page with search and sorting functions)
$('.footable').footable();
//Prepare table2excel plugin (clicking the export button will send the main table to an Excel spreadsheet)
$("button.excelexport").click(function(){
$("#footable").table2excel({
//Exclude CSS class specific to this plugin
exclude: ".noExl",
name: "Merchandising Report",
filename: "merchReportTable"
});
});
});
</script>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.btechco.excelexport.js"></script>
<script src="jquery.base64.js"></script>
<script>
$(document).ready(function() {
$("#btnExport").click(function() {
$("#tblExport1").btechco_excelexport({
containerid: "tblExport1",
datatype: $datatype.Table
});
});
});
</script>
</head>
<body>
<div id="dvd">
<table id="tblExport1" style="border:1px solid black; ">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td style='background-color:red;'>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
<tr>
<td>4</td>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
<div>
<button id="btnExport">Export to excel</button>
</div>
</body>
</html>