前端js实现打印表格

3,278 阅读2分钟

本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。

学习过程中将笔记整理跟大家分享,希望对大家也有所帮助,共同成长进步💪~
如果大家喜欢,可以点赞或留言💕~~~~,谢谢大家⭐️⭐️⭐️~~~ 做的一个简单的小demo,具体需求和样式可以根据自己的样式去修改哦~具体代码如下:

html部分

<div class="tools">
        <button type="button" id="excell" onclick="tableexport('dataTable')">导出表格</button>
</div>
<div class="table_title">未参与住户报表</div>
<div class="Export_people">导出人:张张</div>
<table class="table table-bordered" id="dataTable">
        <thead class="aa">
                <tr>
                        <th>序号</th>
                        <th>街道</th>
                        <th>小区</th>
                        <th>楼号</th>
                        <th>单元号</th>
                        <th>门牌号</th>
                        <th>参与状态</th>
                </tr>
        </thead>
        <tbody class="units">

        </tbody>
</table>

css部分

.table {
        width: 80%;
}
table tr,
th,
td {
        text-align: center;
}
table tr th {
        background: pink;
}
.tdpadding {
        padding: 0 !important;
}
.table_title {
        width: 80%;
        text-align: center;
        border-top: 1px solid grey;
}
.Export_people {
        width: 80%;
        text-align: right;
        border-top: 1px solid grey;
}

js部分

var data = [{
        a: "小明111",
        b: "hhhhh"
}, {
        a: "小明22",
        b: "hhhhh"
}, {
        a: "小明333",
        b: "hhhhh"
}, {
        a: "小明444",
        b: "hhhhh"
}, {
        a: "小明555",
        b: "hhhhhhhhhh"
}, {
        a: "小明666",
        b: "hhhhh"
}]
var str;
for(var i = 0; i < data.length; i++) {
        str += "<tr><td class='bg'>" + data[i].a + "</td><td>" + data[i].b + "</td></tr>"
}
$("#dataTable").append(str)

//打印表格
var idTmr;
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';
        }
}

function tableexport(tableid) {
        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();
}
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) {
                        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
                }
                window.location.href = uri + base64(format(template, ctx))
        }
})()

完整代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
	<script type="text/javascript" src="../../js/jquery-1.12.1.min.js"></script>
	<style>
		.table {
			width: 80%;
		}
		table tr,
		th,
		td {
			text-align: center;
		}
		table tr th {
			background: pink;
		}
		.tdpadding {
			padding: 0 !important;
		}
		.table_title {
			width: 80%;
			text-align: center;
			border-top: 1px solid grey;
		}
		.Export_people {
			width: 80%;
			text-align: right;
			border-top: 1px solid grey;
		}
	</style>
	<body>
		<div class="tools">
			<button type="button" id="excell" onclick="tableexport('dataTable')">导出表格</button>
		</div>
		<div class="table_title">未参与住户报表</div>
		<div class="Export_people">导出人:张张</div>
		<table class="table table-bordered" id="dataTable">
			<thead class="aa">
				<tr>
					<th>序号</th>
					<th>街道</th>
					<th>小区</th>
					<th>楼号</th>
					<th>单元号</th>
					<th>门牌号</th>
					<th>参与状态</th>
				</tr>
			</thead>
			<tbody class="units">
				
			</tbody>
		</table>
	</body>
	<script>
		var data = [{
                        a: "小明111",
                        b: "hhhhh"
                }, {
                        a: "小明22",
                        b: "hhhhh"
                }, {
                        a: "小明333",
                        b: "hhhhh"
                }, {
                        a: "小明444",
                        b: "hhhhh"
                }, {
                        a: "小明555",
                        b: "hhhhhhhhhh"
                }, {
                        a: "小明666",
                        b: "hhhhh"
                }]
		var str;
		console.log(data)
		for(var i = 0; i < data.length; i++) {
			str += "<tr><td class='bg'>" + data[i].a + "</td><td>" + data[i].b + "</td></tr>"
		}
		$("#dataTable").append(str)

		//打印表格
		var idTmr;
		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';
			}
		}

		function tableexport(tableid) {
			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();
		}
		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) {
					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
				}
				window.location.href = uri + base64(format(template, ctx))
			}
		})()
	</script>
</html>

效果图:

image.png

评论抽奖

欢迎在评论区讨论,掘金官方将在掘力星计划活动结束后,在评论区抽送100份掘金周边

  • 抽奖礼物:100份,掘金官方提供,包括掘金徽章、拖鞋、马克杯、帆布袋等,随机发放
  • 抽奖时间:「掘力星计划」活动结束后,预计3个工作日内,官方将在所有符合规则的活动文章评论区抽出
  • 抽奖方式:掘金官方随机抽奖+人工核实
  • 评论内容:与文章内容相关的评论、建议、讨论等,「踩踩」「学习了」等泛泛类的评论无法获奖

专栏推荐

推荐一下自己的专栏,欢迎大家收藏关注😊~