我一直在研究一些能够执行此操作的 jQuery 插件。我决定使用 http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html 的那个并且我已尽可能严格地按照其说明进行操作。我一直在测试这个插件,但每次我点击导出按钮时,都没有任何反应。该表是使用 PHP(从 MySQL 服务器提取数据)填充的,以下是我目前使用的脚本。
<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>
在我添加新代码后,footable
显示完全没有改变。我能做些什么?我一直认为我只是放错了 table2excel block ,但即使我将它放在 ready(function(){})
block 中,也没有任何反应。
最佳答案
这是您可以做的最好的方法。您也可以指定文件名进行下载。只需将 tableid,sheet name,file name 传递给下面的函数,它就会下载。也可以在 IE 中查看 fiddle 下载。
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);}
关于javascript - 将 HTML 表格导出到 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957737/