Saturday, 6 July 2013

Export Gridview Data to Excel in ASP.NET


In this article I will show you how to gridviewexport to excel in asp.net C#.NET. first you need to create a new web project or WebSite. Create a gridview on page, and write code to bind the gridview.

protected void btnGenerateExcel_Click(object sender, ImageClickEventArgs e)
    {
            DataSet DataSetName=new DataSet();
            DataSetName = // Assign Data to DataSet
            GridView.DataSource = DataSetName;
            GridView.DataBind();
            ExportToExcel("Report.xlsx", GridView);
           }


private void ExportToExcel(string strFileName, GridView dg)
    {
        Response.Clear();
        Response.Buffer = true;

        // Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.ContentType = "application/vnd.ms-excel";
        Response.Charset = "";
        this.EnableViewState = false;
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

        gvDefaultersDetails.RenderControl(oHtmlTextWriter);

        Response.Write(oStringWriter.ToString());
        Response.End();

    }

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

If you are facing any problem with Update panel, you can remove update panel

(Or)

You can remove update panel on top and place it the post back event. See the below code.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
               <asp:ImageButton ID="btnGenerateExcel" runat="server"                                                        OnClick="btnGenerateExcel_Click" ImageUrl="~/Images/submitbluebutton.gif" align="Center" />
        </ContentTemplate>
</asp:UpdatePanel>



No comments:

Post a Comment