Gridview export to CSV
In this lesson we are going to export GridView data to a .CSV file.



Default.aspx page code:-

  

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <center> 
    <div>
        <h1>Export to CSV:-</h1>
    <asp:GridView ID="Gridview1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
        <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
        <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
        <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
        <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#FFF1D4" />
        <SortedAscendingHeaderStyle BackColor="#B95C30" />
        <SortedDescendingCellStyle BackColor="#F1E5CE" />
        <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
        <br />
   
        <asp:Button ID="btnExportCSV" runat="server" Text="Export to CSV" Font-Bold="true" Width="186px" OnClick="btnExportCSV_Click" />
    </div>
            </center>
    </form>
</body>
</html>




Default.aspx.cs page code:-

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;

public partial class Default3 : System.Web.UI.Page
{
    string connectionString = "Data Source=PS-PC\\SANTOSH;Initial Catalog=dbSantoshTest;Integrated Security=True";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadRecord();
        }

    }
    protected void loadRecord()
    {
        SqlConnection con = new SqlConnection(connectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from tblRecord", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        int count = ds.Tables[0].Rows.Count;
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            Gridview1.DataSource = ds;
            Gridview1.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            Gridview1.DataSource = ds;
            Gridview1.DataBind();
            int columncount = Gridview1.Rows[0].Cells.Count;
           
        }
    }


    public override void VerifyRenderingInServerForm(Control control)
    {
        /*Tell the compiler that the control is rendered
         * explicitly by overriding the VerifyRenderingInServerForm event.*/
    }

    protected void btnExportCSV_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=gvtocsv.csv");
        Response.Charset = "";
        Response.ContentType = "application/text";
        StringBuilder sBuilder = new System.Text.StringBuilder();
        for (int index = 0; index < Gridview1.Columns.Count; index++)
        {
            sBuilder.Append(Gridview1.Columns[index].HeaderText + ',');
        }
        sBuilder.Append("\r\n");
        for (int i = 0; i < Gridview1.Rows.Count; i++)
        {
            for (int k = 0; k < Gridview1.HeaderRow.Cells.Count; k++)
            {
                sBuilder.Append(Gridview1.Rows[i].Cells[k].Text.Replace(",", "") + ",");
            }
            sBuilder.Append("\r\n");
        }
        Response.Output.Write(sBuilder.ToString());
        Response.Flush();
        Response.End();
    }
}



Output:-