Net-informations.com
SiteMap  | About    

Export ASP.NET to Excel

The following program shows how to export from a GridView data to an Excel file.

export-excel

vb.net

  GridView1.RenderControl(hWriter)

C#

  GridView1.RenderControl(hWriter);

The RenderControl method outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.

vb.net
  Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

End Sub

C#
  public override void VerifyRenderingInServerForm(Control control)
  {

}

The above method will confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

Somtimes you will get an exception unless you are not declared the above method in your program, the exception shows like :

System.Web.HttpException: Control GridView1 of type GridView must be placed inside a form tag with runat=server.

The following ASP.NET program load the data from database to Gridview control and then you can export the data to an Excel file.

Default.aspx

  

<!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 id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
	<form id="form1" runat="server">
	<div>
	<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" />
	<asp:SqlDataSource ID="SqlDataSource1" runat="server"
	ConnectionString="<%$ ConnectionStrings:SQLDbConnection %>"
	SelectCommand="select * from stores" />
	</div>
	<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
	Text="Export to Excel" Width="117px" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	<asp:Label ID="Label1" runat="server" Text="Error Message : "></asp:Label>
</form>
</body>
</html>


Click the following links to see full source code

C# Source Code
VB.NET Source Code
default.aspx.cs
default.aspx.vb





net-informations.com (C) 2016    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.