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-Spreadsheet-using-jQuery-table2excel.html and I've followed its instructions as closely as possible. I've been testing this plugin but every time I click the button to export, nothing happens. The table is populated using PHP (which is pulling data from a MySQL server) and the following is the script I currently have in place.
<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").click(function(){
$(".footable").table2excel({
//Exclude CSS class specific to this plugin
exclude: ".noExl",
name: "Excel Document Name"
});
});
</script>
The footable display hasn't changed at all after I added the new code. What can I do? I keep thinking I've just misplaced the table2excel block but even when I had it inside the ready(function(){}) block, nothing happened.
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);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With