How to Export Gridview Data to CSV in Asp.net | ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial

How to Export Gridview Data to CSV in Asp.net

Introduction: In this article I will explain how we can Export the Gridview Data to CSV in Asp.net
Description:
In last article I have explained How to Bind Gridview in Asp.net.

Take a new website. Add a webform to website and design .aspx page as shown below:
<body>
    <form id="form1" runat="server">
    <div>
     <table>
    <tr><td>&nbsp;</td><td align="right">
        <asp:Button ID="Button1" runat="server" Text="Export To CSV"
            onclick="Button1_Click" /></td></tr>
    <tr><td>&nbsp;</td><td> <asp:GridView ID="grdstudent" runat="server" AutoGenerateColumns="false" DataKeyNames="STUDENT_ID" DataSourceID="SqlDataSource1">
        <Columns>
        <asp:BoundField DataField="STUDENT_NAME" HeaderText="STUDENT NAME" />
        <asp:BoundField DataField="STUDENT_ADDRESS" HeaderText="STUDENT ADDRESS" />
        <asp:BoundField DataField="STUDENT_CLASS" HeaderText="STUDENT CLASS" />
        </Columns>
        </asp:GridView></td></tr>
    </table>
      
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:TestBlogConnectionString %>"
            SelectCommand="SELECT * FROM [STUDENT_DETAIL]"></asp:SqlDataSource>
    </div>
    </form>
</body>


Now go to .aspx.cs page and write the below given code:
using System.Text;

public override void VerifyRenderingInServerForm(Control control)
    {
        // Verifies that the control is rendered
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", string.Format("attachment;filename=StudentDetail's.csv"));
            Response.Charset = "";
            Response.ContentType = "application/text";
            grdstudent.AllowPaging = false;
            grdstudent.DataBind();
            StringBuilder SB = new StringBuilder();
            for (int v = 0; v < grdstudent.Columns.Count; v++)
            {
                //Separting header columns text
                SB.Append(grdstudent.Columns[v].HeaderText + ',');
            }
            //appending new line for gridview
            SB.Append("\r\n");
            for (int i = 0; i < grdstudent.Rows.Count; i++)
            {
                for (int v = 0; v < grdstudent.Columns.Count; v++)
                {
                    //separating gridview columns with comma
                    SB.Append(grdstudent.Rows[i].Cells[v].Text + ',');
                }
                //append new line for gridview
                SB.Append("\r\n");
            }
            Response.Output.Write(SB.ToString());          
            Response.End();
        }
        catch (Exception ex)
        {
        }
    }

In VB (.aspx.vb)
Imports System.Text

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        ' verify that an HtmlForm control is rendered
    End Sub
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Response.ClearContent()
            Response.Buffer = True
            Response.AddHeader("content-disposition", String.Format("attachment;filename=StudentDetail's.csv"))
            Response.Charset = ""
            Response.ContentType = "application/text"
            grdstudent.AllowPaging = False
            grdstudent.DataBind()
            Dim SB As New StringBuilder()
            For v As Integer = 0 To grdstudent.Columns.Count - 1
                'Separting header columns text
                SB.Append(grdstudent.Columns(v).HeaderText + ","c)
            Next
            'appending new line for gridview
            SB.Append(vbCr & vbLf)
            For i As Integer = 0 To grdstudent.Rows.Count - 1
                For v As Integer = 0 To grdstudent.Columns.Count - 1
                    'separating gridview columns with comma
                    SB.Append(grdstudent.Rows(i).Cells(v).Text + ","c)
                Next
                'separating gridview columns with comma
                sb.Append(vbCr & vbLf)
            Next
            Response.Output.Write(sb.ToString())
            Response.End()
        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:


http://articlemirror.blogspot.in/2013/07/control-grdstudent-of-type-gridview.html

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget