直接使用(两种方式)
1.下载插件:
地址:github table2excel
下载下来项目后,在项目的dist
中就有该js,在自己表格html页面引用即可使用。
链接:百度云下载js
提取码:1f52
/** * 使用方法该js的方法(两行代码) */ let table2excel = new Table2Excel(); // 传入你的tableId即可导出 table2excel.export($('#tableId'), "your filename");
2.一个解析页面元素方法:
复制走即可使用
/** * * @param id:表格的id * @param fileName:导出的excel的名字 */ function exportForExcle(id,fileName){ var table = $(document.getElementById(id)).clone(); table.attr('id','datatab'); table.appendTo('body'); method5('datatab'); datatab.remove(); function method5(tableid) { var idTmr; var tableToExcel = (function() { var uri = 'data:application/vnd.ms-excel;base64,', template = '<html><head><meta charset="UTF-8"></head><body><table border="1px">{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, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} var aTag = document.createElement('a'); aTag.download = fileName; aTag.href = uri + base64(format(template, ctx)); document.body.appendChild(aTag); aTag.onclick = function () { document.body.removeChild(aTag); } aTag.click(); } })() if(getExplorer()=='ie') { var curTbl = document.getElementById(tableid); var oXL = new ActiveXObject("Excel.Application"); var oWB = oXL.Workbooks.Add(); var xlsheet = oWB.Worksheets(1); var sel = document.body.createTextRange(); sel.moveToElementText(curTbl); sel.select(); sel.execCommand("Copy"); xlsheet.Paste(); oXL.Visible = true; try { var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls"); } catch (e) { print("Nested catch caught " + e); } finally { oWB.SaveAs(fname); oWB.Close(savechanges = false); oXL.Quit(); oXL = null; idTmr = window.setInterval("Cleanup();", 1); } } else { tableToExcel(tableid) } function Cleanup() { window.clearInterval(idTmr); CollectGarbage(); } function getExplorer() { var explorer = window.navigator.userAgent ; //ie if (explorer.indexOf("MSIE") >= 0) { return 'ie'; } //firefox else if (explorer.indexOf("Firefox") >= 0) { return 'Firefox'; } //Chrome else if(explorer.indexOf("Chrome") >= 0){ return 'Chrome'; } //Opera else if(explorer.indexOf("Opera") >= 0){ return 'Opera'; } //Safari else if(explorer.indexOf("Safari") >= 0){ return 'Safari'; } } } }
原文来自于:https://blog.csdn.net/weixin_45237517/article/details/100119628