Thursday, 20 February 2014

Gridview Export To Excel In Asp.Net C#

In this article i will show you how to gridview export to excel in asp.net c#. For this first your need to create a new web project. Add a gridview on page, and write code to bind the gridview. So for binding the gridview please check the below link:


Now for export to excel follow the code:

protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString());
            SqlDataAdapter objda = new SqlDataAdapter("select * from AreaTable", objcon);
            objda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }






















The above code is used for binding the grid view .
After binding the code add a new button and generate a click event of the button. Add the following code in button click event.


    protected void btndownload_Click(object sender, EventArgs e)
        {          
            DataTable dt = new DataTable();
            SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString());
            SqlDataAdapter objda = new SqlDataAdapter("select * from AreaTable", objcon);
            objda.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            ExportToExcel("Report.xls", GridView1);
            GridView1 = null;
            GridView1.Dispose();

        }

private void ExportToExcel(string strFileName, GridView gv)
        {
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
            Response.ContentType = "application/excel";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }


Now save the page and click on button DOWNLOAD . What happen :) ...You will get an error

Control `GridView1` of type `GridView` must be placed inside a form tag with runat=server.

So for removing this error you have to override VerifyRenderingInServerForm. Now add the below mention code:


public override void VerifyRenderingInServerForm(Control control)
        {
            /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
               server control at run time. */
        }

Now press F5 and click on download button:

You will now able to export your data in excel file.


Now click on save or open. your data will appear as shown below.


Tags: Asp.Net , C#.Net , GridView , MS Sql Sever , VB.Net

No comments:

Post a Comment