在导出Excle否者是Word时,我在网上搜集到有两种方法,其中一种是可以导出页面控件的方法(我认为是比较简单的方法),代码如下:
.aspx页面代码:
Code
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>导出数据的页面</title>
</head>
<body style="text-align: center">
<form id="form1" runat="server">
<div align="left" runat="server" >
<asp:GridView ID="gvShow" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvShow_RowDataBound"
ShowFooter="True" AllowPaging="True" PageSize="5" OnPageIndexChanging="gvShow_PageIndexChanging">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="name" HeaderText="种类" />
<asp:BoundField DataField="number" HeaderText="个数" />
<asp:BoundField DataField="je" HeaderText="金额" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnOut" runat="server" Text="导出数据" OnClick="btnOut_Click" />
</div>
</form>
</body>
</html>
后台.aspx.cs代码:
后台代码(借鉴了博友彭建军的方法)
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
属性#region 属性
private int sum1 = 0;
private double sum2 = 0;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.bindtopinfo();
}
}
加载数据#region 加载数据
/**//// <summary>
/// 绑定GridView
/// </summary>
private void bindtopinfo()
{
string strConn = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(strConn);
if (conn.State.Equals(ConnectionState.Closed))
{
conn.Open();
}
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand("select * from PInfo", conn);
DataSet ds = new DataSet();
sda.Fill(ds, "PInfo");
this.gvShow.DataSource = ds.Tables["PInfo"];
this.gvShow.DataBind();
}
protected void gvShow_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text != null || e.Row.Cells[2].Text != "")
{
sum1 += Convert.ToInt32(e.Row.Cells[2].Text);
sum2 += Convert.ToInt32(e.Row.Cells[3].Text);
}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "合计:";
e.Row.Cells[2].Text = "合计:" + sum1;
e.Row.Cells[3].Text = "合计:" + sum2;
}
}
protected void gvShow_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.gvShow.PageIndex = e.NewPageIndex;
this.bindtopinfo();
}
#endregion
导出页面或web控件方法#region 导出页面或web控件方法
/**//// <summary>
/// 将Web控件或页面信息导出(不带文件名参数)
/// </summary>
/// <param name="source">控件实例</param>
/// <param name="DocumentType">导出类型:Excel或Word</param>
public void ExportControl(System.Web.UI.Control source, string DocumentType)
{
//设置Http的头信息,编码格式
if (DocumentType == "Excel")
{
//Excel
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("下载文件.xls", System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-excel";
}
else if (DocumentType == "Word")
{
//Word
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("下载文件.doc", System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-word";
}
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
//关闭控件的视图状态
source.Page.EnableViewState = false;
//初始化HtmlWriter
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
source.RenderControl(htmlWriter);
//输出
HttpContext.Current.Response.Write(writer.ToString());
HttpContext.Current.Response.End();
}
/**//// <summary>
/// 将Web控件或页面信息导出(带文件名参数)
/// </summary>
/// <param name="source">控件实例</param>
/// <param name="DocumentType">导出类型:Excel或Word</param>
/// <param name="filename">保存文件名</param>
public void ExportControl(System.Web.UI.Control source, string DocumentType, string filename)
{
//设置Http的头信息,编码格式
if (DocumentType == "Excel")
{
//Excel
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode(filename+".xls",System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-excel";
}
else if (DocumentType == "Word")
{
//Word
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode(filename+".doc",System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-word";
}
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
//关闭控件的视图状态
source.Page.EnableViewState =false;
//初始化HtmlWriter
System.IO.StringWriter writer = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
source.RenderControl(htmlWriter);
//输出
HttpContext.Current.Response.Write(writer.ToString());
HttpContext.Current.Response.End();
}
#endregion
导出GridView中的数据#region 导出GridView中的数据
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
protected void btnOut_Click(object sender, EventArgs e)
{
this.gvShow.AllowPaging = false;
this.bindtopinfo();
ExportControl(this.gvShow, "Excel", "testfilename");
this.gvShow.AllowPaging = true;
}
#endregion
}
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
属性#region 属性
private int sum1 = 0;
private double sum2 = 0;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.bindtopinfo();
}
}
加载数据#region 加载数据
/**//// <summary>
/// 绑定GridView
/// </summary>
private void bindtopinfo()
{
string strConn = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
SqlConnection conn = new SqlConnection(strConn);
if (conn.State.Equals(ConnectionState.Closed))
{
conn.Open();
}
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand("select * from PInfo", conn);
DataSet ds = new DataSet();
sda.Fill(ds, "PInfo");
this.gvShow.DataSource = ds.Tables["PInfo"];
this.gvShow.DataBind();
}
protected void gvShow_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[2].Text != null || e.Row.Cells[2].Text != "")
{
sum1 += Convert.ToInt32(e.Row.Cells[2].Text);
sum2 += Convert.ToInt32(e.Row.Cells[3].Text);
}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[0].Text = "合计:";
e.Row.Cells[2].Text = "合计:" + sum1;
e.Row.Cells[3].Text = "合计:" + sum2;
}
}
protected void gvShow_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.gvShow.PageIndex = e.NewPageIndex;
this.bindtopinfo();
}
#endregion
导出页面或web控件方法#region 导出页面或web控件方法
/**//// <summary>
/// 将Web控件或页面信息导出(不带文件名参数)
/// </summary>
/// <param name="source">控件实例</param>
/// <param name="DocumentType">导出类型:Excel或Word</param>
public void ExportControl(System.Web.UI.Control source, string DocumentType)
{
//设置Http的头信息,编码格式
if (DocumentType == "Excel")
{
//Excel
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("下载文件.xls", System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-excel";
}
else if (DocumentType == "Word")
{
//Word
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("下载文件.doc", System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-word";
}
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
//关闭控件的视图状态
source.Page.EnableViewState = false;
//初始化HtmlWriter
System.IO.StringWriter writer = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
source.RenderControl(htmlWriter);
//输出
HttpContext.Current.Response.Write(writer.ToString());
HttpContext.Current.Response.End();
}
/**//// <summary>
/// 将Web控件或页面信息导出(带文件名参数)
/// </summary>
/// <param name="source">控件实例</param>
/// <param name="DocumentType">导出类型:Excel或Word</param>
/// <param name="filename">保存文件名</param>
public void ExportControl(System.Web.UI.Control source, string DocumentType, string filename)
{
//设置Http的头信息,编码格式
if (DocumentType == "Excel")
{
//Excel
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode(filename+".xls",System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-excel";
}
else if (DocumentType == "Word")
{
//Word
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode(filename+".doc",System.Text.Encoding.UTF8));
HttpContext.Current.Response.ContentType = "application/ms-word";
}
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
//关闭控件的视图状态
source.Page.EnableViewState =false;
//初始化HtmlWriter
System.IO.StringWriter writer = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
source.RenderControl(htmlWriter);
//输出
HttpContext.Current.Response.Write(writer.ToString());
HttpContext.Current.Response.End();
}
#endregion
导出GridView中的数据#region 导出GridView中的数据
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
protected void btnOut_Click(object sender, EventArgs e)
{
this.gvShow.AllowPaging = false;
this.bindtopinfo();
ExportControl(this.gvShow, "Excel", "testfilename");
this.gvShow.AllowPaging = true;
}
#endregion
}
这里有一个地方,就是在后台要加上
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
为什么呢?如果不加上就会出现这样的错误:控件“GridView”必须放在具有 runat=server 的窗体标记内。
MSDN对该方法的解释如下:
必须位于 <form runat=server> 标记中的控件可以在呈现之前调用此方法,以便在控件被置于标记外时显示错误信息。发送回或依赖于注册的脚本块的控件应该在 Control.Render 方法的重写中调用此方法。呈现服务器窗体元素的方式不同的页可以重写此方法以在不同的条件下引发异常。
如果回发或使用客户端脚本的服务器控件没有包含在 HtmlForm 服务器控件 ( <form runat="server">) 标记中,它们将无法正常工作。这些控件可以在呈现时调用该方法,以在它们没有包含在 HtmlForm 控件中时提供明确的错误信息。
开发自定义服务器控件时,通常在为任何类型的输入标记重写 Render 方法时调用该方法。这在输入控件调用 GetPostBackEventReference 或发出客户端脚本时尤其重要。复合服务器控件不需要作出此调用。