} catch (e) { alert(e.description); } } //非IE浏览器导出Excel var HtmlExportToExcelForEntire = (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, name) { if (!table.nodeType) { table = document.getElementById(table); } var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML} var $a=$("<a id='exportToExcel' href='"+uri + base64(format(template, ctx))+"' download='"+name+".xls'></a>"); $('body').append($a); document.getElementById("exportToExcel").click(); $a.remove(); } })() 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'; } } 以上代码作为插件引入 layui table.render中加入以下代码 生产隐藏的table dom元素 done : function(res, curr, count) { //res接口返回的信息;curr得到当前页码;count得到数据总量 //合并单元格 兼容ie8 layuiRowspan(['unitname'],1);//支持数组 createExportDomFun('unitEconomicRunTable'); } var execRowspan = function(fieldName,index,flag){ // 1为不冻结的情况,左侧列为冻结的情况 var fixedNode; fixedNode = index=="1"?$(".layui-table-body")[index - 1]:(index=="3"?$(".layui-table-fixed-r"):$(".layui-table-fixed-l")); // 左侧导航栏不冻结的情况 var child = $(fixedNode).find("td"); var childFilterArr = []; // 获取data-field属性为fieldName的td for(var i = 0; i < child.length; i++){ if(child[i].getAttribute("data-field") == fieldName){ childFilterArr.push(child[i]); } } // 获取td的个数和种类 var childFilterTextObj = {}; for(var i = 0; i < childFilterArr.length; i++){ //var childText = flag?childFilterArr[i].innerHTML:childFilterArr[i].textContent; var childText = childFilterArr[i].innerText; //console.log(childText); if(childFilterTextObj[childText] == undefined){ childFilterTextObj[childText] = 1; }else{ var num = childFilterTextObj[childText]; childFilterTextObj[childText] = num*1 + 1; } } var canRowspan = true; var maxNum;//以前列单元格为基础获取的最大合并数 var finalNextIndex;//获取其下第一个不合并单元格的index var finalNextKey;//获取其下第一个不合并单元格的值 for(var i = 0; i < childFilterArr.length; i++){ (maxNum>9000||!maxNum)&&(maxNum = $(childFilterArr[i]).prev().attr("rowspan")&&fieldName!="8"?$(childFilterArr[i]).prev().attr("rowspan"):9999); //var key = flag?childFilterArr[i].innerHTML:childFilterArr[i].textContent;//获取下一个单元格的值 var key = childFilterArr[i].innerText;//获取下一个单元格的值 var nextIndex = i+1; var tdNum = childFilterTextObj[key]; var curNum = maxNum<tdNum?maxNum:tdNum; if(canRowspan){ for(var j =1;j<=curNum&&(i+j<childFilterArr.length);){//循环获取最终合并数及finalNext的index和key //finalNextKey = flag?childFilterArr[i+j].innerHTML:childFilterArr[i+j].textContent; finalNextKey = childFilterArr[i+j].innerText; finalNextIndex = i+j; if((key!=finalNextKey&&curNum>1)||maxNum == j){ canRowspan = true; curNum = j; break; } j++; if((i+j)==childFilterArr.length){ finalNextKey=undefined; finalNextIndex=i+j; break; } } childFilterArr[i].setAttribute("rowspan",curNum); if($(childFilterArr[i]).find("div.rowspan").length>0){//设置td内的div.rowspan高度适应合并后的高度 $(childFilterArr[i]).find("div.rowspan").parent("div.layui-table-cell").addClass("rowspanParent"); $(childFilterArr[i]).find("div.layui-table-cell")[0].style.height= curNum*38-10 +"px"; } canRowspan = false; }else{ childFilterArr[i].style.display = "none"; } if(--childFilterTextObj[key]==0|--maxNum==0|--curNum==0|(finalNextKey!=undefined&&nextIndex==finalNextIndex)){//||(finalNextKey!=undefined&&key!=finalNextKey) canRowspan = true; } } } //合并数据表格行 var layuiRowspan = function(fieldNameTmp,index,flag){ var fieldName = []; if(typeof fieldNameTmp == "string"){ fieldName.push(fieldNameTmp); }else{ fieldName = fieldName.concat(fieldNameTmp); } for(var i = 0;i<fieldName.length;i++){ execRowspan(fieldName[i],index,flag); } } function createExportDomFun(id){ var header_tr = $('#'+id+'').next().find(".layui-table-header").find("tr"); var body_tr = $('#'+id+'').next().find(".layui-table-body").find("tr"); var header_html = ""; var body_html = ""; // 获取表头html,包括单元格的合并 $.each(header_tr,function (i,tr) { var header_th = $(tr).find("th"); header_html += "<tr>"; $.each(header_th,function (j,th) { var rowspan_num = $(th).attr("rowspan");// 行合并数 var colspan_num = $(th).attr("colspan");// 列合并数 if (rowspan_num && !colspan_num){// 只有行合并时 header_html += '<th rowspan= "'+ rowspan_num +'">'; } else if (colspan_num && !rowspan_num){// 只有列合并时 header_html += '<th colspan= "'+ colspan_num +'">'; } else if (rowspan_num && colspan_num){// 行列合并均有时 header_html += '<th rowspan= "'+ rowspan_num +'" colspan="'+ colspan_num +'">'; } else {// 没有发生单元格合并 header_html += '<th>'; } header_html += $(th).children().children().text() + '</th>';// 获取表头名称并拼接th标签 }) header_html += '</tr>'; }) // 获取表格body数据 $.each(body_tr,function (i,tr) { var body_td = $(tr).find("td"); body_html += '<tr>'; $.each(body_td,function (j,td) { body_html += '<td>' + $(td).children().text() + '</td>'; }) body_html += '</tr>'; }) $('#'+id+' tr').remove();// 清除之前的doom结构 $('#'+id+'').append(header_html).append(body_html); $('#'+id+'').hide(); }
前端表格导出-layui复杂表头导出支持ie8+
//jQuery HTML导出Excel文件(兼容IE及所有浏览器)//传入需要导出的table的id
function HtmlExportToExcel(tableid,filename) {
//var filename = $('.datatitle').text();
if (getExplorer() == 'ie' || getExplorer() == undefined) {
HtmlExportToExcelForIE(tableid, filename);
}else {
HtmlExportToExcelForEntire(tableid, filename)
}
}
//IE浏览器导出Excel
function HtmlExportToExcelForIE(tableid, filename) {
try {
var curTbl = document.getElementById(tableid);
var oXL;
try{
oXL = new ActiveXObject("Excel.Application"); //创建AX对象excel
}catch(e){
alert("无法启动Excel!\n\n如果您确信您的电脑中已经安装了Excel,"+"那么请调整IE的安全级别。\n\n具体操作:\n\n"+"工具 → Internet选项 → 安全 → 自定义级别 → 对没有标记为安全的ActiveX进行初始化和脚本运行 → 启用");
return false;
}
var oWB = oXL.Workbooks.Add(); //获取workbook对象
var oSheet = oWB.ActiveSheet;//激活当前sheet
var sel = document.body.createTextRange();
sel.moveToElementText(curTbl); //把表格中的内容移到TextRange中
try{
sel.select(); //全选TextRange中内容
}catch(e1){
e1.description
}
sel.execCommand("Copy");//复制TextRange中内容
oSheet.Paste();//粘贴到活动的EXCEL中
oXL.Visible = true; //设置excel可见属性
var fname = oXL.Application.GetSaveAsFilename(filename+".xls", "Excel Spreadsheets (*.xls), *.xls");
oWB.SaveAs(fname);
oWB.Close();
oXL.Quit();