Export GridView Records to CSV Using ASP.Net C#

Background

There is often a need in a project's reporting module to export Grid View records to CSV, So by considering that requirement I decided to write this article especially focusing on beginners and those who want to learn how to export a Grid View to CSV using ASP.NET C#.

Now before creating the application, let us create a table named employee in a database from where we show the records in a Grid View, the table has the following fields (shown in the following image): 
 


I hope you have created the same type of table.

Now create the project
as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".

  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).

  3. Provide the Project name such as ExportGridRecordsToCSV or another as you wish and specify the location.

  4. Then right-click on Solution Explorer and select "Add New Item" then select Default.aspx page.

  5. One Button and a grid view.
Now the Default.aspx source code will be as follows: 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExPortGridviewToXML.Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html>  
  5. <head id="Head1" runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body bgcolor="Silver">  
  9.     <form id="form1" runat="server">  
  10.     <br />  
  11.     <h2 style="color: #808000; font-size: x-large; font-weight: bolder;">  
  12.         Article by Vithal Wadje</h2>  
  13.     <br />  
  14.     <div>  
  15.         <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" CellPadding="6"  
  16.             ForeColor="#333333" GridLines="None">  
  17.             <AlternatingRowStyle BackColor="White" />  
  18.             <EditRowStyle BackColor="#7C6F57" />  
  19.             <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  20.             <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  21.             <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
  22.             <RowStyle BackColor="#E3EAEB" />  
  23.             <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />  
  24.             <SortedAscendingCellStyle BackColor="#F8FAFA" />  
  25.             <SortedAscendingHeaderStyle BackColor="#246B61" />  
  26.             <SortedDescendingCellStyle BackColor="#D4DFE1" />  
  27.             <SortedDescendingHeaderStyle BackColor="#15524A" />  
  28.             <Columns>  
  29.                 <asp:BoundField DataField="id" HeaderText="id" />  
  30.                 <asp:BoundField DataField="Name" HeaderText="Name" />  
  31.                 <asp:BoundField DataField="City" HeaderText="City" />  
  32.                 <asp:BoundField DataField="Address" HeaderText="Address" />  
  33.                 <asp:BoundField DataField="Designation" HeaderText="Designation" />  
  34.             </Columns>  
  35.         </asp:GridView>  
  36.         <br />  
  37.                    <asp:Button ID="Button1" runat="server"  
  38.             Text="Export" OnClick="Button1_Click" />  
  39.     </div>  
  40.     </form>  
  41. </body>  
  42. </html> 

Now let us create a function to bind the records to the Grid View from the database. If you are a beginner and don't understand in detail how to bind a Grid View from a database then refer to my following article.

Now, for this article create the following function in the default.aspx.cs page to bind the Grid View:
  1. private void Bindgrid()  
  2.       {  
  3.           connection();  
  4.           query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security  
  5.           com = new SqlCommand(query, con);  
  6.           SqlDataAdapter da = new SqlDataAdapter(query, con);  
  7.           DataSet ds = new DataSet();             
  8.           da.Fill(ds);  
  9.           GridView1.DataSource = ds;  
  10.           GridView1.DataBind();  
  11.           con.Close();  
  12.             
  13.       } 
Now, call the preceding function on page load as:
  1. protected void Page_Load(object sender, EventArgs e)  
  2.        {  
  3.            if (!IsPostBack)  
  4.            {  
  5.                Bindgrid();  
  6.   
  7.            }  
  8.        } 
Now create the following function to export the Grid View records to CSV:
  1. private void ExportGridToCSV()  
  2.        {  
  3.            Bindgrid();  
  4.            Response.Clear();  
  5.            Response.Buffer = true;  
  6.            Response.AddHeader("content-disposition""attachment;filename=Vithal_Wadje.csv");  
  7.            Response.Charset = "";  
  8.            Response.ContentType = "application/text";  
  9.            GridView1.AllowPaging = false;  
  10.            GridView1.DataBind();  
  11.             
  12.            StringBuilder columnbind = new StringBuilder();  
  13.            for (int k = 0; k < GridView1.Columns.Count; k++)  
  14.            {  
  15.                 
  16.                columnbind.Append(GridView1.Columns[k].HeaderText + ',');  
  17.            }  
  18.             
  19.            columnbind.Append("\r\n");  
  20.            for (int i = 0; i < GridView1.Rows.Count; i++)  
  21.            {  
  22.                for (int k = 0; k < GridView1.Columns.Count; k++)  
  23.                {  
  24.                      
  25.                    columnbind.Append(GridView1.Rows[i].Cells[k].Text + ',');  
  26.                }  
  27.                
  28.                columnbind.Append("\r\n");  
  29.            }  
  30.            Response.Output.Write(columnbind.ToString());  
  31.            Response.Flush();  
  32.            Response.End();  
  33.           
  34.        } 
We have created the preceding function to export GridView Records to CSV. Now call the preceding function on the Export button click as:
  1. protected void Button1_Click(object sender, EventArgs e)  
  2.        {  
  3.   
  4.            ExportGridToCSV();  
  5.   
  6.        } 
The entire code of the default.aspx page will look as follows: 
  1. using System;  
  2. using System.IO;  
  3. using System.Data;  
  4. using System.Threading;  
  5. using System.Data.SqlClient;  
  6. using System.Configuration;  
  7. using System.Text;  
  8. using System.Web.UI.WebControls;  
  9.   
  10. namespace ExPortGridviewToXML  
  11. {  
  12.     public partial class Default : System.Web.UI.Page  
  13.     {  
  14.         private SqlConnection con;  
  15.         private SqlCommand com;  
  16.         private string constr, query;  
  17.         private void connection()  
  18.         {  
  19.             constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
  20.             con = new SqlConnection(constr);  
  21.             con.Open();  
  22.   
  23.         }  
  24.         protected void Page_Load(object sender, EventArgs e)  
  25.         {  
  26.             if (!IsPostBack)  
  27.             {  
  28.                 Bindgrid();  
  29.   
  30.             }  
  31.         }  
  32.   
  33.   
  34.         private void Bindgrid()  
  35.         {  
  36.             connection();  
  37.             query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security  
  38.             com = new SqlCommand(query, con);  
  39.             SqlDataAdapter da = new SqlDataAdapter(query, con);  
  40.             DataSet ds = new DataSet();             
  41.             da.Fill(ds);  
  42.             GridView1.DataSource = ds;  
  43.             GridView1.DataBind();  
  44.             con.Close();  
  45.               
  46.         }  
  47.           
  48.         protected void Button1_Click(object sender, EventArgs e)  
  49.         {  
  50.   
  51.             ExportGridToCSV();  
  52.   
  53.         }  
  54.         private void ExportGridToCSV()  
  55.         {  
  56.             Bindgrid();  
  57.             Response.Clear();  
  58.             Response.Buffer = true;  
  59.             Response.AddHeader("content-disposition""attachment;filename=Vithal_Wadje.csv");  
  60.             Response.Charset = "";  
  61.             Response.ContentType = "application/text";  
  62.             GridView1.AllowPaging = false;  
  63.             GridView1.DataBind();  
  64.              
  65.             StringBuilder columnbind = new StringBuilder();  
  66.             for (int k = 0; k < GridView1.Columns.Count; k++)  
  67.             {  
  68.                  
  69.                 columnbind.Append(GridView1.Columns[k].HeaderText + ',');  
  70.             }  
  71.              
  72.             columnbind.Append("\r\n");  
  73.             for (int i = 0; i < GridView1.Rows.Count; i++)  
  74.             {  
  75.                 for (int k = 0; k < GridView1.Columns.Count; k++)  
  76.                 {  
  77.                       
  78.                     columnbind.Append(GridView1.Rows[i].Cells[k].Text + ',');  
  79.                 }  
  80.                 
  81.                 columnbind.Append("\r\n");  
  82.             }  
  83.             Response.Output.Write(columnbind.ToString());  
  84.             Response.Flush();  
  85.             Response.End();  
  86.            
  87.         }  
  88.   
  89.          
  90.     }  

Now run the application and then we can see the following records in the Grid view:
 
 
Now click on the export button, the following Popup will appear:
 
 
 
 Now click the OK button, the following records are exported to the CSV file:
 
 
 
Now you see that all the records of the Grid View are exported to  CSV file.

Notes
  • Download the Zip file from the attachment for the full source code of the application.
  • Change the connection string in the web.config file to specify your server location.
Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also. 

Up Next
    Ebook Download
    View all
    Learn
    View all