How to Export Gridview Data to Excel in - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

How to Export Gridview Data to Excel in

Introduction: In this article I will explain how we can Export the Gridview Data to Excel in
Take a new website. Add a webform to website and design .aspx page as shown below:
    <form id="form1" runat="server">
    <tr><td>&nbsp;</td><td align="right">
        <asp:Button ID="Button1" runat="server" Text="Export To Excel"
            onclick="Button1_Click" /></td></tr>
    <tr><td>&nbsp;</td><td> <asp:GridView ID="grdstudent" runat="server" AutoGenerateColumns="false" DataKeyNames="STUDENT_ID" DataSourceID="SqlDataSource1">
        <asp:BoundField DataField="STUDENT_NAME" HeaderText="STUDENT NAME" />
        <asp:BoundField DataField="STUDENT_ADDRESS" HeaderText="STUDENT ADDRESS" />
        <asp:BoundField DataField="STUDENT_CLASS" HeaderText="STUDENT CLASS" />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:TestBlogConnectionString %>"
            SelectCommand="SELECT * FROM [STUDENT_DETAIL]"></asp:SqlDataSource>

Now go to .aspx.cs page and write the below given code:
public override void VerifyRenderingInServerForm(Control control)
        // Verifies that the control is rendered
    protected void Button1_Click(object sender, EventArgs e)
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "StudentDetail.xls"));          
            Response.ContentType = "application/ms-excel";
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            grdstudent.AllowPaging = false;
        catch (Exception ex)

In VB (.aspx.vb)

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        ' Verifies that the control is rendered
    End Sub
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
            Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "StudentDetail.xls"))
            Response.ContentType = "application/ms-excel"
            Dim sw As New System.IO.StringWriter()
            Dim htw As New HtmlTextWriter(sw)
            grdstudent.AllowPaging = False
        Catch ex As Exception
        End Try

    End Sub

If you get any error "Control 'grdstudent' of type 'GridView' must be placed inside a form tag with runat=server" read this article:

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+