表格样式
前台js方法:代码里面的注释很详细,简单说一下我这里是有一个table,id为aa
function importExcel() {
var tableid = "aa";
tableToExcel(tableid);
};
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html><head><meta charset="UTF-8"></head><body><table border="1">{table}</table></body></html>',
base64 = function(
s) {
return window.btoa(unescape(encodeURIComponent(s)))
},
format = function(s, c) {
debugger;
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
})
}
return function(table, name) {
var thead = $t("thead").clone();//待导出的表头
var tbody = $("#aa").clone();//待导出的内容
var thead1 = thead;
var tbody1 = tbody;
var theadHtml = "";
var tbodyHtml = "";
//我这里设置了隐藏列 所以需要删除 可以根据 自己的需要重新拼接 需要导出excel
//删除表头的隐藏列 这里可以直接remove 因为 这是克隆的
for(var i=0;i<4;i++){
$(thead1).find("th").eq(0).remove();
};
//这个是移除没选的
$(tbody1).find("tr").each(function(i,n){
debugger;
if(!$(n).find("td").eq(0).find("input").attr("checked")){
$(n).remove();
}
});
//删除表格的隐藏列 这里可以直接remove 因为 这是克隆的
$(tbody1).find("tr").each(function(i,n){
for(var j=0;j<4;j++){
$(n).find("td").eq(0).remove();
};
});
theadHtml = $(thead1).html();
tbodyHtml = $(tbody1).html();
//拼接需要导出的excel
var tableHtml = theadHtml+tbodyHtml;
var ctx = {
worksheet: name || 'Worksheet',
table: tableHtml
}
//方法1:直接下载
window.location.href = uri + base64(format(template, ctx))//不修改下载excel名就可以用这个
//方法2:写一个隐藏的a标签,id 是exportExcel
//document.getElementById("exportExcel").href = uri + base64(format(template, ctx));
//document.getElementById("exportExcel").download = "机务桥载明细结算清单导出为Excel";//这里是修改下载的excel名称
//document.getElementById("exportExcel").click();
}
})()