请问如何将GridView1中的数据通过点击Button1导出到excel中,谢谢!
//report02.aspx
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="report02.aspx.cs" Inherits="UnicomReportSystem._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BCVConnectionString %>"
ProviderName="<%$ ConnectionStrings:BCVConnectionString.ProviderName %>" SelectCommand="select * from table_a"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCC99" />
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="SERVICE_ID"
SortExpression="ID" />
<asp:BoundField DataField="NAME" HeaderText="DEALER_NAME"
SortExpression="NAME" />
<asp:BoundField DataField="FEE" HeaderText="FEE" SortExpression="FEE" />
</Columns>
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" Text="导出" />
</form>
</body>
</html>//----------------------------------------------------------------------
//report02.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;namespace UnicomReportSystem
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
}
}
//report02.aspx
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="report02.aspx.cs" Inherits="UnicomReportSystem._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BCVConnectionString %>"
ProviderName="<%$ ConnectionStrings:BCVConnectionString.ProviderName %>" SelectCommand="select * from table_a"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCC99" />
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="SERVICE_ID"
SortExpression="ID" />
<asp:BoundField DataField="NAME" HeaderText="DEALER_NAME"
SortExpression="NAME" />
<asp:BoundField DataField="FEE" HeaderText="FEE" SortExpression="FEE" />
</Columns>
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" Text="导出" />
</form>
</body>
</html>//----------------------------------------------------------------------
//report02.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;namespace UnicomReportSystem
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
}
}
{
// Confirms that an HtmlForm control is rendered for
} public static void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}参考
http://blog.xunbin.com/Article/22.aspx
{
HttpContext.Current.Response.Charset = "BIG5";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
} public override void VerifyRenderingInServerForm(Control control)
{ }
编译错误
说明: 在编译向该请求提供服务所需资源的过程中出现错误。请检查下列特定错误详细信息并适当地修改源代码。 编译器错误消息: CS0123: “Button1_Click”的重载均与委托“System.EventHandler”不匹配源错误: 行 40: </asp:GridView>
行 41: <br />
行 42: <asp:Button ID="Button1" runat="server" Text="导出" onclick="Button1_Click"/>
行 43: </form>
行 44: </body>
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
/*加下面這一句,導出前讓它不能分頁*/
GridView1.AllowPaging = false;
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();/*再加這一句,導出后讓它再分頁*/
GridView1.AllowPaging = true;
/// <summary>
/// 导出dataGrid 中的数据
/// </summary>
/// <param name="exportobject">导出数据的对象,可以是Datagrid,或page</param>
/// <param name="attachName">文件名称</param>
/// <param name="exportTypeId">1:excel;2:word;3:txt;4:html</param>
public void ExportDataGridData(Control[] control,string fileName,int exportTypeId)
{
Response.Clear();
Response.Buffer= true;
Response.Charset="utf-8";
string headerValue = "attachment;" + fileName + "=";//.xls"
Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
//Response.ContentType指定文件类型 可以为application/ms-excel || application/ms-word || application/ms-txt || application/ms-html || 或其他浏览器可直接支持文档
if(exportTypeId == 1)
{
headerValue += ".xls";
Response.ContentType = "application/vnd.ms-excel";
}
else if(exportTypeId == 2)
{
headerValue += ".doc";
Response.ContentType = "application/vnd.ms-word";
}
else if(exportTypeId == 3)
{
headerValue += ".txt";
Response.ContentType = "application/vnd.ms-txt";
}
else if(exportTypeId == 4)
{
headerValue += ".html";
Response.ContentType = "application/vnd.ms-html";
}
else
{
headerValue += ".xls";
Response.ContentType = "application/vnd.ms-excel";
}
Response.AppendHeader("Content-Disposition",headerValue);
Response.Charset = ""; //关闭 ViewState
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。
//此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
//获取control的HTML
foreach(Control con in control)
{
if(con != null)
{
if(con is DataGrid)
{
if(((DataGrid)con).Items.Count > 0)
{
con.RenderControl(hw);//将DATAGRID中的内容输出到HtmlTextWriter对象中
}
}
else
{
con.RenderControl(hw);
}
}
}
// 把HTML写回浏览器
Response.Write(tw.ToString());
Response.End();
}
------------
下面代码实现将 GridView 导出到 Excel文件中。值得注意的是VerifyRenderingInServerForm重载方法:
MSDN上的 VerifyRenderingInServerForm 方法的描述:
必须位于 <form runat=server> 标记中的控件可以在呈现之前调用此方法,以便在控件被置于标记外时显示错误信息。发送回或依赖于注册的脚本块的控件应该在 Control.Render 方法的重写中调用此方法。呈现服务器窗体元素的方式不同的页可以重写此方法以在不同的条件下引发异常。
如果回发或使用客户端脚本的服务器控件没有包含在 HtmlForm 服务器控件 (<form runat="server">) 标记中,它们将无法正常工作。这些控件可以在呈现时调用该方法,以在它们没有包含在 HtmlForm 控件中时提供明确的错误信息。
开发自定义服务器控件时,通常在为任何类型的输入标记重写 Render 方法时调用该方法。这在输入控件调用 GetPostBackEventReference 或发出客户端脚本时尤其重要。复合服务器控件不需要作出此调用。 没有这个方法,程序将报错。C# 代码<%...@ Page Language="C#" EnableEventValidation="false" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">...
ICollection CreateDataSource( )
...{
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("id", typeof(Int32)));
dt.Columns.Add(new System.Data.DataColumn("PkID", typeof(string)));
dt.Columns.Add(new System.Data.DataColumn("Title", typeof(string)));
for (int i = 0; i < 6; i++)
...{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "123456789123456789123456789";
dr[2] = "<a href='http://dotnet.aspx.cc/'>欢迎光临【孟宪会之精彩世界】</a>";
dt.Rows.Add(dr);
}
System.Data.DataView dv = new System.Data.DataView(dt);
return dv;
} protected void Page_Load( object sender, EventArgs e )
...{
if (!IsPostBack)
...{
GridView1.BorderWidth = Unit.Pixel(2);
GridView1.BorderColor = System.Drawing.Color.DarkOrange;
GridView1.DataSource = CreateDataSource();
GridView1.DataBind();
}
} protected void Button1_Click( object sender, System.EventArgs e )
...{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End(); }
public override void VerifyRenderingInServerForm( Control control )
...{ }
protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e )
...{
if (e.Row.RowType == DataControlRowType.DataRow)
...{
e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
}
}
</script><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>将 GridView 导出到 Excel 文件中</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="序号" DataField="id" />
<asp:BoundField HeaderText="身份证号" DataField="PkID" />
<asp:BoundField HeaderText="网址" DataField="Title" ReadOnly="true" HtmlEncode="false" />
</Columns>
</asp:GridView>
<asp:Literal ID="HiddenOut" runat="server" />
<asp:Button ID="Button1" runat="server" Text="导出" OnClick="Button1_Click" />
</form>
</body>
</html>VB.NET 代码<%...@ Page Language="VB" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">...
Function CreateDataSource() As ICollection
Dim dt As System.Data.DataTable = New System.Data.DataTable
Dim dr As System.Data.DataRow
dt.Columns.Add(New System.Data.DataColumn("id", GetType(Int32)))
dt.Columns.Add(New System.Data.DataColumn("PkID", GetType(String)))
dt.Columns.Add(New System.Data.DataColumn("Title", GetType(String)))
Dim i As Integer = 0
While i < 6
dr = dt.NewRow
dr(0) = i
dr(1) = "123456789123456789123456789"
dr(2) = "<a href='http://dotnet.aspx.cc/'>欢迎光临【孟宪会之精彩世界】</a>"
dt.Rows.Add(dr)
System.Math.Min(System.Threading.Interlocked.Increment(i),i-1)
End While
Dim dv As System.Data.DataView = New System.Data.DataView(dt)
Return dv
End Function Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
GridView1.BorderWidth = Unit.Pixel(2)
GridView1.BorderColor = System.Drawing.Color.DarkOrange
GridView1.DataSource = CreateDataSource
GridView1.DataBind
End If
End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Clear
Response.Buffer = True
Response.Charset = "GB2312"
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls")
Response.ContentEncoding = System.Text.Encoding.UTF7
Response.ContentType = "application/ms-excel"
Dim oStringWriter As System.IO.StringWriter = New System.IO.StringWriter
Dim oHtmlTextWriter As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(oStringWriter)
Me.GridView1.RenderControl(oHtmlTextWriter)
Response.Output.Write(oStringWriter.ToString)
Response.Flush
Response.End
End Sub Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(1).Attributes.Add("style", "vnd.ms-excel.numberformat:@;")
End If
End Sub</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>将 GridView 导出到 Excel 文件中</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="序号" DataField="id" />
<asp:BoundField HeaderText="身份证号" DataField="PkID" />
<asp:BoundField HeaderText="网址" DataField="Title" ReadOnly="true" HtmlEncode="false" />
</Columns>
</asp:GridView>
<asp:Literal ID="HiddenOut" runat="server" />
<asp:Button ID="Button1" runat="server" Text="导出" OnClick="Button1_Click" />
</form>
</body>
</html>