Exporting data to CSV File

Introduction

In this example we will export Grid view data populated by Database to CSV File.

This is the html source of the page

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false"  CodeFile="Register.aspx.cs" Inherits="Register" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<
html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="grdDetail" Width="400px" runat="server"
        AutoGenerateColumns="False" AllowPaging="true" PageSize="5" 
        BackColor="White" BorderColor="White" BorderStyle="Ridge"
        BorderWidth="2px" CellPadding="3" CellSpacing="1" DataKeyNames="Id"
         GridLines="None" AllowSorting="true" >
        <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
        <Columns>
         
            <asp:BoundField DataField="Name" HeaderText="Name"  />
            <asp:BoundField DataField="EmpId" HeaderText="EmpId" />
            <asp:BoundField DataField="ContactNo" HeaderText="ContactNo" />
            <asp:BoundField DataField="EmailId" HeaderText="EmailId" />
            <asp:BoundField DataField="Address" HeaderText="Address" />
        </Columns>
        <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
        <PagerStyle BackColor="#C6C3C6" ForeColor="Black"      HorizontalAlign="Right" />
        <SelectedRowStyle BackColor="#9471DE" Font-Bold="True"   ForeColor="White" />
        <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
    </asp:GridView>
        <asp:Button ID="Export" runat="server" Text="Export To CSV" onclick="Export_Click" />
    </div>
    </form>
</body>
</
html>

The complete code of Register.aspx.cs Page in Code Behind:

using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

public partial class Register : System.Web.UI.Page
{
    DataTable dtCsv = new DataTable();
    BAL objBAL = new BAL();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            fillgrid();
        }  
    }
    public void fillgrid()
    {
        DataSet ds = new DataSet();
        ds = objBAL.Fill_Grid();//Function defined in BAL Class
        dtCsv = ds.Tables[0];       
        grdDetail.DataSource = ds.Tables[0]; 
        grdDetail.DataBind();
       
    }
 
    protected void btnExport_Click(object sender, EventArgs e)
    {
        fillgrid();
        CreateCSVFile(dtCsv, "c:\\" + "Register" + ".csv" + ""); 
    }
   
    public void CreateCSVFile(DataTable dt, string strFilePath)
    {
        StreamWriter sw = new StreamWriter(strFilePath, false);
        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
       sw.Write(sw.NewLine);
       // Now write all the rows.
       foreach (DataRow dr in dt.Rows)
       {
           for (int i = 0; i < iColCount; i++)
           {
                if (!Convert.IsDBNull(dr[i]))
                {
                     sw.Write(dr[i].ToString());
                 }
                 if (i < iColCount - 1)
                {
                     sw.Write(",");
                 }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }
 
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
}

App_Code BAL.cs

using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data;
public class BAL
{
     public BAL()
     {
          //
          // TODO: Add constructor logic here
          //
     }
 
     #region "variable"
               
     #region "Properties"
     #region "Functions"
     public DataSet Fill_Grid()
     {
         SqlConnection conn = new SqlConnection(connectionString);
         SqlCommand cmd = new SqlCommand("SELECT * from Register", conn);
         cmd.CommandType = CommandType.Text;
         SqlDataAdapter adap = new SqlDataAdapter(cmd);
         DataSet ds = new DataSet();
         adap.Fill(ds);
         return ds;
     }
     #endregion
}