How to Export gridview or repeater data to Excel

Description



You can export the data of gridview to a excel file programmatically.
First add a gridview inside the form tag which must have runat="server"

example:

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>


Bind the grid at page load

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

private void BindGrid()
{
string strFillgird = //yopur query
//create a dataset here
GridView1.DataSource = dsRecord;
GridView1.DataBind();
}


Call this function to Export data whenever you require like onclick of button or linkbutton


private void ExportData()
{
string FileName = "MyExcel.xls";
//clear buffer
Response.Clear();
//display Download dialog
Response.AddHeader("content-disposition", "attachment;filename=" + FileName + "");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter ioWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(ioWriter);
GridView1.RenderControl(htmlWriter);
Response.Write(ioWriter.ToString());
Response.End();
}

add this method to render gridview control

//If you are using master page
public override void VerifyRenderingInServerForm( Control control )
{
}

Note:Set EnableEventValidation as false

Example:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm46.aspx.cs" Inherits="DermsoftV2.Test.WebForm46" EnableEventValidation = "false"%>


Related Articles

What is GridView control and how to bind GridView to data?

What is a GridView control in asp.net? Want to learn how to connect GridView to a database? This article will teach you more about the databound control GridView, properties and events of GridView and binding a GridView control to data.

How to add Buttons in Data GridView?

Want to add buttons to the GridView control in Asp.net? Need to execute a set of statements when the user clicks on the button in the GridView? Learn how to add controls like button to the GridView control and write C# code for user activities performed like Clicking of Buttons in the GridView.

More articles: Gridview

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: