1、总体思想
A、打印gridview数据:
将gridview绑定的数据放到一个层中,点击打印按钮把层中的所有的信息传递到一个新的页面,然后对此页面进行全屏打印,启用浏览器调用本机的打印机接口。
存在的问题:
如果开启分页,只能打印第一页的数据
如果想打印的数据并不是gridview中的全部展示的列数据,也无法实现
B、导出excel的问题
这个操作太多了不再说明,需要注意的是如果开启分页导出的时候需要关闭分页,并重新绑定数据
2、具体实现
A、层内的绑定的gridview的信息
<div id="printdiv">
<h4 style="width: 699px; text-align:Center"> 钥匙借用登记表</h4>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="182px" Width="700px" DataKeyNames="ID" AllowPaging="true"
OnRowDeleting="GridView1_RowDeleting"
onselectedindexchanged="GridView1_SelectedIndexChanged" onpageindexchanging="GridView1_PageIndexChanging" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" InsertVisible="False" ReadOnly="True" Visible="False" />
<asp:BoundField DataField="Date" HeaderText="日期时间" SortExpression="Date" />
<asp:BoundField DataField="Department" HeaderText="借用部门" SortExpression="Department" />
<asp:BoundField DataField="Reason" HeaderText="借用事由" SortExpression="Reason" />
<asp:BoundField DataField="Amount" HeaderText="借用数量" SortExpression="Amount" />
<asp:BoundField DataField="Borrower" HeaderText="借用人" SortExpression="Borrower" />
<asp:BoundField DataField="Tel" HeaderText="联系电话" SortExpression="Tel" />
<asp:BoundField DataField="Watch" HeaderText="值班人" SortExpression="Watch" />
<%--<asp:CommandField ShowDeleteButton="True" /> --%>
</Columns>
</asp:GridView>
</div> B、分页的gridview用来展示,全部数据的girdview进行隐藏,而打印的时候选取隐藏的数据,这样可以解决分页无法打印多页的问题。
<script type="text/javascript">
window.onload = function () {
var d1 = document.getElementById('Div1'); //获取该div节点
d1.style.display = 'none'; //值为'none'设置为隐藏。
}
function printPage() {
var newWin = window.open('printer', '', '');
var titleHTML = document.getElementById("Div1").innerHTML;
newWin.document.write(titleHTML);
newWin.document.location.reload();
newWin.print();
newWin.close();
}
</script>C、导出excel的主要代码
protected void Button4_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "gb2312";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.AllowPaging = false;
GridView1.AllowSorting = false;
GridView1.DataBind();
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
GridView1.AllowPaging = true;
GridView1.AllowSorting = true;
GridView1.DataBind();
}
3、效果演示

打印效果:

导出效果:

源码下载地址:
http://download.youkuaiyun.com/download/danqingcheng/10192012
本文介绍如何通过隐藏和显示不同的Gridview来解决打印时的分页问题,并提供导出Excel的具体实现方法。
3690

被折叠的 条评论
为什么被折叠?



