js打印html页面中的指定内容?
文章发布日期: 2017-12-20
文章更新日期:2018-01-08 添加demo下载
下载地址
声明,所有的打印页面都叫,index.html
使用table2excel.js直接下载table数据到excel中
获取table2excel.js文件
使用步骤
- 在html页面中引入jquery,版本要注意。
点开上面的链接,打开table2excel.jquery.json的文件,dependencies(依赖项)要求jquery>=1.4
所以呢,你需要有个jquery,并把它引入到index.html中。我使用的jquery版本是v1.11.3
- 网上随便找一个 table,顺手甩在index.html里。
<table id="dataTable" class="table2excel" data-tableName="Test Table 1">
<thead>
<tr class="noExl"><td>This shouldn't get exported</td><td>This shouldn't get exported either</td></tr>
<tr><td>This Should get exported as a header</td><td>This should too</td></tr>
</thead>
<tbody>
<tr>
<td>data1a with a <a href="#">link one</a> and <a href="#">link two</a>.</td>
<td>data1b with a <img src="image_file.jpg" alt="image">.</td></tr>
<tr>
<td>data2a with a <input tyle="text" value="text value">.</td>
<td>data2b with a <input tyle="text" value="second text value">.</td>
</tr>
</tbody>
<tfoot>
<tr><td colspan="2">This footer spans 2 cells</td></tr>
</tfoot>
</table>
- 在index.html里引入table2excel.js,然后调用,就可以下载了
$(function(){
$(".table2excel").table2excel({
exclude: ".noExl",
name: "Excel Document Name",
filename: "myFileName" + new Date().toISOString().replace(/[\-\:\.]/g, ""),
fileext: ".xls",
exclude_img: true,
exclude_links: true,
exclude_inputs: true
});
});
下载excel,简单实现,带源码,想看就看不看跳过
贴出源码
//打印表格
var idTmr;
function getExplorer() {
var explorer = window.navigator.userAgent;
if(explorer.indexOf("MSIE") >= 0) {
return 'ie';
}else if(explorer.indexOf("Firefox") >= 0) {
return 'Firefox';
}else if(explorer.indexOf("Chrome") >= 0) {
return 'Chrome';
}else if(explorer.indexOf("Opera") >= 0) {
return 'Opera';
}else if(explorer.indexOf("Safari") >= 0) {
return 'Safari';
}
}
function method5(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))
}
})()
使用步骤
直接调用method5()把table的id传进去
如:method5(‘dataTable’)
使用printArea打印table数据,调用浏览器自带打印设备可预览
使用步骤
- 引入jquery,布置好table
布局table时注意,如果想引入table的样式,需嘘嘘
<div id="gridtable">
<style type="text/css">
table.gridtable {
font-family: verdana, arial, sans-serif;
font-size: 11px;
color: #333333;
border-width: 1px;
border-color: #666666;
margin: 0 auto;
border-collapse: collapse;
}
table.gridtable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
}
table.gridtable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
</style>
<table width="90%" class="gridtable">
<caption><h1>XX市医疗保险特药使用申请表</h1></caption>
<tr>
<td colspan='5'>申请单号</td>
<td colspan='2'>申请日期:XXX年XX月XX日</td>
</tr>
<tr>
<td>Info Header 1</td>
<td>Info Header 2</td>
<td>Info Header 3</td>
<td>Info Header 4</td>
<td>Info Header 5</td>
<td>Info Header 6</td>
<td>Info Header 7</td>
</tr>
<tr>
<td>Text 1A</td>
<td>Text 1B</td>
<td>Text 1C</td>
<td>Text 1D</td>
<td>Text 1E</td>
<td>Text 1F</td>
<td>Text 1G</td>
</tr>
<tr>
<td>Text 2A</td>
<td>Text 2B</td>
<td>Text 2C</td>
<td>Text 2D</td>
<td>Text 2E</td>
<td>Text 2F</td>
<td>Text 2G</td>
</tr>
<tr>
<td>Text 3A</td>
<td>Text 3B</td>
<td>Text 3C</td>
<td>Text 3D</td>
<td>Text 3E</td>
<td>Text 3F</td>
<td>Text 3G</td>
</tr>
</table>
</div>
<button id="print">打印</button>
- 获取jquery.printarea.js的源码,并引入
如果使用这个三年前的源码有问题的话,比如打印空白,可以使用下面由其他网友提供的源码,地址见目录‘空白源码’
- 调用printArea()方法
<script>
$("#print").click(function() {
$("#gridtable").printArea();
});
</script>
printArea简单实现源码,想看就看,不看跳过
(function($) {
var printAreaCount = 0;
var removePrintArea = function(id) {
$("iframe#" + id).remove();
};
$.fn.printArea = function() {
var ele = $(this);
var idPrefix = "printArea_";
removePrintArea(idPrefix + printAreaCount);
printAreaCount++;
var iframeId = idPrefix + printAreaCount;
var iframeStyle = 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;';
iframe = document.createElement('IFRAME');
$(iframe).attr({
style: iframeStyle,
id: iframeId
});
// 把iframe放到body中
document.body.appendChild(iframe);
// 获取iframe的document的属性
var doc = iframe.contentWindow.document;
doc.open(); // 开启
// 获取当前窗口的css文件并引入到iframe中
$(document).find("link").filter(function() {
return $(this).attr("rel").toLowerCase() == "stylesheet";
}).each(function() {
doc.write('<link type="text/css" rel="stylesheet" href="' +
$(this).attr("href") + '" >');
});
// 展示要打印的内容
doc.write('<div class="' + $(ele).attr("class") + '">' + $(ele).html() +
'</div>');
doc.close(); // 关闭
var frameWindow = iframe.contentWindow;
frameWindow.close();
frameWindow.focus();
frameWindow.print();
}
})(jQuery);
空白源码
(function($) {
var counter = 0;
var modes = {
iframe: "iframe",
popup: "popup"
};
var standards = {
strict: "strict",
loose: "loose",
html5: "html5"
};
var defaults = {
mode: modes.iframe,
standard: standards.html5,
popHt: 500,
popWd: 400,
popX: 200,
popY: 200,
popTitle: '',
popClose: false,
extraCss: '',
extraHead: '',
retainAttr: ["id", "class", "style"]
};
var settings = {}; //global settings
$.fn.printArea = function(options) {
$.extend(settings, defaults, options);
counter++;
var idPrefix = "printArea_";
$("[id^=" + idPrefix + "]").remove();
settings.id = idPrefix + counter;
var $printSource = $(this);
var PrintAreaWindow = PrintArea.getPrintWindow();
PrintArea.write(PrintAreaWindow.doc, $printSource);
setTimeout(function() {
PrintArea.print(PrintAreaWindow);
}, 1000);
};
var PrintArea = {
print: function(PAWindow) {
var paWindow = PAWindow.win;
$(PAWindow.doc).ready(function() {
paWindow.focus();
paWindow.print();
if(settings.mode == modes.popup && settings.popClose)
setTimeout(function() {
paWindow.close();
}, 2000);
});
},
write: function(PADocument, $ele) {
PADocument.open();
PADocument.write(PrintArea.docType() + "<html>" + PrintArea.getHead() + PrintArea.getBody($ele) + "</html>");
PADocument.close();
},
docType: function() {
if(settings.mode == modes.iframe) return "";
if(settings.standard == standards.html5) return "<!DOCTYPE html>";
var transitional = settings.standard == standards.loose ? " Transitional" : "";
var dtd = settings.standard == standards.loose ? "loose" : "strict";
return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01' + transitional + '//EN" "http://www.w3.org/TR/html4/' + dtd + '.dtd">';
},
getHead: function() {
var extraHead = "";
var links = "";
if(settings.extraHead) settings.extraHead.replace(/([^,]+)/g, function(m) {
extraHead += m
});
$(document).find("link")
.filter(function() { // Requirement: <link> element MUST have rel="stylesheet" to be considered in print document
var relAttr = $(this).attr("rel");
return($.type(relAttr) === 'undefined') == false && relAttr.toLowerCase() == 'stylesheet';
})
.filter(function() { // Include if media is undefined, empty, print or all
var mediaAttr = $(this).attr("media");
return $.type(mediaAttr) === 'undefined' || mediaAttr == "" || mediaAttr.toLowerCase() == 'print' || mediaAttr.toLowerCase() == 'all'
})
.each(function() {
links += '<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" >';
});
if(settings.extraCss) settings.extraCss.replace(/([^,\s]+)/g, function(m) {
links += '<link type="text/css" rel="stylesheet" href="' + m + '">'
});
return "<head><title>" + settings.popTitle + "</title>" + extraHead + links + "</head>";
},
getBody: function(elements) {
var htm = "";
var attrs = settings.retainAttr;
elements.each(function() {
var ele = PrintArea.getFormData($(this));
var attributes = ""
for(var x = 0; x < attrs.length; x++) {
var eleAttr = $(ele).attr(attrs[x]);
if(eleAttr) attributes += (attributes.length > 0 ? " " : "") + attrs[x] + "='" + eleAttr + "'";
}
htm += '<div ' + attributes + '>' + $(ele).html() + '</div>';
});
return "<body>" + htm + "</body>";
},
getFormData: function(ele) {
var copy = ele.clone();
var copiedInputs = $("input,select,textarea", copy);
$("input,select,textarea", ele).each(function(i) {
var typeInput = $(this).attr("type");
if($.type(typeInput) === 'undefined') typeInput = $(this).is("select") ? "select" : $(this).is("textarea") ? "textarea" : "";
var copiedInput = copiedInputs.eq(i);
if(typeInput == "radio" || typeInput == "checkbox") copiedInput.attr("checked", $(this).is(":checked"));
else if(typeInput == "text" || typeInput == "") copiedInput.attr("value", $(this).val());
else if(typeInput == "select")
$(this).find("option").each(function(i) {
if($(this).is(":selected")) $("option", copiedInput).eq(i).attr("selected", true);
});
else if(typeInput == "textarea") copiedInput.text($(this).val());
});
return copy;
},
getPrintWindow: function() {
switch(settings.mode) {
case modes.iframe:
var f = new PrintArea.Iframe();
return {
win: f.contentWindow || f,
doc: f.doc
};
case modes.popup:
var p = new PrintArea.Popup();
return {
win: p,
doc: p.doc
};
}
},
Iframe: function() {
var frameId = settings.id;
var iframeStyle = 'border:0;position:absolute;width:0px;height:0px;right:0px;top:0px;';
var iframe;
try {
iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).attr({
style: iframeStyle,
id: frameId,
src: "#" + new Date().getTime()
});
iframe.doc = null;
iframe.doc = iframe.contentDocument ? iframe.contentDocument : (iframe.contentWindow ? iframe.contentWindow.document : iframe.document);
} catch(e) {
throw e + ". iframes may not be supported in this browser.";
}
if(iframe.doc == null) throw "Cannot find document.";
return iframe;
},
Popup: function() {
var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar=no,dependent=no";
windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=yes";
var newWin = window.open("", "_blank", windowAttr);
newWin.doc = newWin.document;
return newWin;
}
};
})(jQuery);
最后,甩一个printArea的demo,copy直接用,注意引入jquery
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="printArea2.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="gridtable">
<style type="text/css">
table.gridtable {
font-family: verdana, arial, sans-serif;
font-size: 11px;
margin: 0 auto;
color: #333333;
border-color: #666666;
border-collapse: collapse;
}
table.gridtable td {
border-width: 1px;
padding: 8px;
text-align:center;
border-style: solid;
border-color: #666666;
background-color: #ffffff;
}
table.gridtable tr.first,table.gridtable tr.first td{
border-width: 0;
}
table.gridtable tr.first td.fl{
text-align: left;
text-align: -moz-left;
text-align: -webkit-left;
}
table.gridtable tr.first td.fr{
text-align: right;
text-align: -moz-right;
text-align: -webkit-right;
}
table.gridtable td.text-left{
text-align: left;
padding-left: 30px;
}
table.gridtable td.gender {
width:80px;
}
table.gridtable td.last {
border-width: 0;
}
table.gridtable td.pd_btm_2px{
padding-bottom: 2px;
}
span.checkBox{
position: relative;
padding-left: 25px;
margin-right: 10px;
}
span.checkBox:before{
content: "";
display: inline-block;
position: absolute;
top:1px;
left: 5px;
width: 11px;
height: 11px;
border:1px solid #ccc;
}
.timefr{
padding-top: 15px;
margin-right: 30px;
float: right;
}
.textfl{
float: left;
display: block;
text-align: left;
}
</style>
<table width="90%" height="90%" class="gridtable">
<caption><h1>_____市医疗保险特药使用申请表</h1></caption>
<tr class="first">
<td class="fl" colspan='5'>申请单号:</td>
<td class="fr" colspan='2'>申请日期:XXX年XX月XX日</td>
</tr>
<tr>
<td>姓名</td>
<td colspan='2'>张三</td>
<td>性别</td>
<td class="gender">男</td>
<td>年龄</td>
<td>28</td>
</tr>
<tr>
<td>社会保障卡卡号</td>
<td colspan='2'>123456789</td>
<td>身份证号</td>
<td colspan='3'>412326499216452135</td>
</tr>
<tr>
<td>人员类别</td>
<td class="text-left" colspan="6">
<span class="checkBox">职工医保</span>
<span class="checkBox">居民医保</span>
</td>
</tr>
<tr>
<td>参保属地</td>
<td colspan='2'>南京</td>
<td>联系电话</td>
<td colspan='3'>17312278695</td>
</tr>
<tr>
<td>工作单位</td>
<td class="text-left" colspan="6">南京德益康有限公司</td>
</tr>
<tr>
<td>家庭住址</td>
<td class="text-left" colspan="6">南京德益康有限公司</td>
</tr>
<tr>
<td>申请使用用品名称</td>
<td colspan='2'>沙丹红</td>
<td>疾病诊断</td>
<td colspan='3'>谈鸟病</td>
</tr>
<tr>
<td>指定医院</td>
<td colspan='2'>南京市红十字医院</td>
<td>责任医生</td>
<td colspan='3'>李建用</td>
</tr>
<tr>
<td>确诊时间</td>
<td colspan='2'>2017-12-17</td>
<td>身高(cm)</td>
<td colspan='3'>178</td>
</tr>
<tr>
<td>体重(kg)</td>
<td colspan='2'>60</td>
<td>BSA(m^2)</td>
<td colspan='3'>1.78</td>
</tr>
<tr>
<td>提供附件名称</td>
<td class="text-left" colspan="6">
<span class="checkBox">CT报告</span>
<span class="checkBox">血常规报告</span>
<span class="checkBox">基因检测</span>
</td>
</tr>
<tr rowspan="2">
<td class="pd_btm_2px" colspan="7">
<span class="textfl">申请人签字(患者本人):</span><br>
<span class="timefr"> 年 月 日</span>
</td>
</tr>
<tr rowspan="2">
<td class="pd_btm_2px" colspan="7">
<span class="textfl">申请人签字(患者本人):</span><br>
<div style="clear:both;"></div>
<span class="textfl">协助药房盖章:</span><br>
<span class="timefr"> 年 月 日</span>
</td>
</tr>
<tr rowspan="3">
<td class="last" colspan="7">
<span class="textfl">注:1、本表一式两份,协助药房、参保患者各持一份。</span><br>
<div style="clear:both;"></div>
<span class="textfl"> 2、需提供的材料:社会保障卡、患者近期一寸免冠彩照、门诊特定项目(门诊大病)证、相关医疗文书(基因检测(必要时)、病理诊断、影像报告、门诊病历、出院小结)等材料。</span><br>
<div style="clear:both;"></div>
<span class="textfl"> 3、本表私自涂改或复印无效。</span>
</td>
</tr>
</table>
</div>
<button id="print">打印</button>
<script>
$("#print").click(function() {
$("#gridtable").printArea();
});
</script>
</body>
</html>
最最后在贴一个比较好看的表格,不负责解决中文乱码
<div id="printArea">
<style type="text/css">
table {
border-collapse: collapse;
margin: 0 auto;
text-align: center;
}
table td,
table th {
border: 1px solid #cad9ea;
color: #666;
height: 30px;
}
table thead th {
background-color: #CCE8EB;
width: 100px;
}
table tr:nth-child(odd) {
background: #fff;
}
table tr:nth-child(even) {
background: #F5FAFA;
}
</style>
<table width="90%" class="table">
<caption>
<h2>
车间能源消耗比例</h2>
</caption>
<thead>
<tr>
<th>车间</th>
<th>产量</th>
<th>电量</th>
<th>单耗</th>
</tr>
</thead>
<tr>
<td>109</td>
<td>13</td>
<td>1.34</td>
<td>213</td>
</tr>
<tr>
<td>109</td>
<td>13</td>
<td>1.34</td>
<td>213</td>
</tr>
<tr>
<td>109</td>
<td>13</td>
<td>1.34</td>
<td>213</td>
</tr>
<tr>
<td>109</td>
<td>13</td>
<td>1.34</td>
<td>213</td>
</tr><tr>
<td>109</td>
<td>13</td>
<td>1.34</td>
<td>213</td>
</tr>
<tr>
<td>109</td>
<td>13</td>
<td>1.34</td>
<td>213</td>
</tr>
</table>
</div>