JS代码:
/** * table数据导出到excel * 形参 table : tableId ; * sheetName : 工作薄名 * fileName : 文件名 * linkId :隐藏的链接控件id */ var tableToExcel = (function () { var uri = 'data:application/vnd.ms-excel;base64,', template = '<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]--></head><body><table>{table}</table></body></html>', base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))); }, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }); } return function (table, sheetName, fileName,linkId) { if (!table.nodeType) table = document.getElementById(table); var ctx = { worksheet: sheetName || 'Worksheet', table: table.innerHTML } var dlinkInfo = document.getElementById(linkId); dlinkInfo.href = uri + base64(format(template, ctx)); dlinkInfo.download = fileName; dlinkInfo.click(); } })();
使用样例:
html部分代码
<div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <div class="container"> <div class="row"> <div class="col-md-6"> <h4 class="modal-title" id="myModalLabel"></h4> </div> <div class="col-md-4"> <h4 class="modal-title" id="tipMessageLabel"></h4> </div> <div class="col-md-2"> <input type="button" onClick="exportDataToExcel()" value="导出到Excel" class="btn btn-primary"> <a id="dlink" style="display: none;"></a> </div> </div> </div> </div> <div style=" height:550px; overflow:scroll;"> <table class="col-lg-12 table table-striped table-bordered" id="relatedBaseInfoTable" style="max-height: 500px"></table> </div>
JS代码
var exeExportDataToExcel = function () { var sheetName = $("#tipMessageLabel").html(); var fileName = $("#myModalLabel").html() + ".xls"; tableToExcel("relatedBaseInfoTable", sheetName, fileName, "dlink"); }