---
title: "打印gridview "
author: "fastwind"
date: "2008-06-10T16:01:33Z"
tags: []
slug: "gridview"
draft: false
lastmod: "2008-06-10T16:01:33Z"
id: 201806
url: "https://fastwind.iteye.com/blog/201806"
---

打印指定内容：

 

代码就是这样的.

```
<html>
<head>
<script type="text/javascript" language="javascript">
function printPage() {
var newWin = window.open('printer.html','','');
var titleHTML = document.getElementById("printdiv").innerHTML;
newWin.document.write(titleHTML);
newWin.document.location.reload();
newWin.print();

newWin.close();
}
</script>
</head>
<body>
<div id="printdiv">
<table class="sontable" cellspacing="0" cellpadding="0" style="width: 13%">
<tr>
<td style="width: 700px; height: 161px">
<asp:GridView ID="GridData" runat="server" CellPadding="3" CellSpacing="0" BorderWidth="1px" BackColor="LightSteelBlue" BorderColor="White" BorderStyle="None" Font-Size="12px" Width="543px" Height="20px" OnRowDataBound="GridData_RowDataBound">
<RowStyle BackColor="GhostWhite" BorderColor="#006699" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" Wrap="True" />
<HeaderStyle Height="25px" BackColor="#006699" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" CssClass="Freezing"/>
</asp:GridView>  
</td>
</tr>
</table>
</div>
<a href="javascript:;" onclick="printPage()">打印</a>
</body>
</html>
 
```

   
这里的实现原理是将GridView里的内容放到另一个Web页面中然后执行打印！

第二种方法是,先将页面上的除了你要打印的标签外隐藏,接着执行打印,在打印后将页面上的标签全部显示

代码如下:  
function printer()  
{  
　　  
 beforeprint();  
 window.focus();  
 window.print()  
 afterprint();  
}

function beforeprint()  
{

 for(i = 0; i &lt; document.all.length; i++)  
 {  
   
  if ((document.all(i).id.indexOf("div\_table\_")!=-1) && document.all(i).tagName=="TABLE")

//其中"div\_table\_"检测你要打印的标签ID  
  {  
  document.all(i).style.display="none";  
  }  
 }  
}

function afterprint()  
{

 for(i = 0; i &lt; document.all.length; i++)  
 {  
  if ((document.all(i).id.indexOf("div\_table\_")!=-1) && document.all(i).tagName=="TABLE")  
  {  
  document.all(i).style.display="block";  
  }  
 }  
}

调用printer()就可以了