Site icon ParallelCodes

ASP.NET GridView Export to CSV File

In this post I’ll share a simple class which you can integrate in your code to Export ASP.NET GridView to CSV or Excel sheet file.

Below is the class code for you to directly use.  You have to pass the Id(name) of your ASP.NET GridView to this class and the file name with which you want to export the file. The file will be downloaded with the given filename in the client’s default download folder and with the GridView data in it.

ASP.NET GridView to CSV file – Classcode : 

public void CSV(GridView dataGrid, String fileName)
{
try
{
string txt = string.Empty;

for (int i = 0; i < dataGrid.HeaderRow.Cells.Count; i++)
{
txt += dataGrid.HeaderRow.Cells[i].Text.ToString() + ",";
}
txt += "\r\n";
foreach (GridViewRow row in dataGrid.Rows)
{
foreach (TableCell cell in row.Cells)
{
txt += cell.Text + ","; //Add the Data rows.
}
txt += "\r\n"; //Add new line.
}

Response.Clear(); //Download the Text file.
HttpContext.Current.Response.Buffer = true;
String dateTime = System.DateTime.Now.ToString("ddMMyyyyhhmmss");
String g = fileName + dateTime + ".csv";

Response.AddHeader("content-disposition", "attachment;filename='" + g + "'");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(txt);
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (System.Threading.ThreadAbortException ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
Debug.WriteLine(ex.InnerException.ToString());
Thread.ResetAbort();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message.ToString());
}
}

Output :

My ASP.NET GridView :

ASP.NET GridView to CSV file – GridView with Data.

GridView CSV file :

ASP.NET GridView to CSV file – CSV with Data.

Class Usage :

I will show how to use this class inside your ASP.NET Web application.

My ASPX page :

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>GridView to CSV</title>
<style>
body
{
font-family:Arial;
background-color:lightyellow;
}
</style>
</head>
<body >
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="dataGrid1" BackColor="White" BorderColor="#999999"
BorderStyle="None" BorderWidth="1px" CellPadding="5" GridLines="Vertical" >
<AlternatingRowStyle BackColor="#DCDCDC" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black"/>
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>

<br /><br />
<asp:Button runat="server" Text="Export" ID="btnExport" OnClick="btnExport_Click"/>
</div>
</form>
</body>
</html>

 

My Class file :

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Threading;

public partial class GridViewtoCSV : System.Web.UI.Page
{
static String connectionString = "Data Source=192.168.0.192;Initial Catalog=ParallelCodes;User ID=sa;Password=789";
SqlConnection con;
SqlCommand cmd;
static DataTable dt;
SqlDataAdapter sqlAdapter;
SqlDataAdapter sqlReader;
static DataSet dsPosts;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
FillGrid();
}

public void FillGrid()
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand("Select Id,ProName as [Product], ProDesc as [Description] from Producttbl", con);
sqlAdapter = new SqlDataAdapter(cmd);
dt = new DataTable();
sqlAdapter.Fill(dt);
dataGrid1.DataSource = dt;
dataGrid1.DataBind();
con.Close();
}

public void CSV(GridView dataGrid, String fileName)
{
try
{
string txt = string.Empty;

for (int i = 0; i < dataGrid.HeaderRow.Cells.Count; i++)
{
txt += dataGrid.HeaderRow.Cells[i].Text.ToString() + ",";
}
txt += "\r\n";
foreach (GridViewRow row in dataGrid.Rows)
{
foreach (TableCell cell in row.Cells)
{
txt += cell.Text + ","; //Add the Data rows.
}
txt += "\r\n"; //Add new line.
}

Response.Clear(); //Download the Text file.
HttpContext.Current.Response.Buffer = true;
String dateTime = System.DateTime.Now.ToString("ddMMyyyyhhmmss");
String g = fileName + dateTime + ".csv";

Response.AddHeader("content-disposition", "attachment;filename='" + g + "'");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(txt);
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (System.Threading.ThreadAbortException ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
Debug.WriteLine(ex.InnerException.ToString());
Thread.ResetAbort();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message.ToString());
}
}
protected void btnExport_Click(object sender, EventArgs e)
{
CSV(dataGrid1, "myfile");
}
}

 

This will produce below output on clicking the export button :

ASP.NET GridView to CSV file – CSV with Data.

Also see :

Gridview with updatepanel in Asp.net C#

Gridview with delete button in asp.net

Gridview checkbox in Asp.net c#

GridView with Buttons ASP.NET C#

STYLING THE GRIDVIEW IN ASP.NET

How to fill data in gridview in asp net

 


Exit mobile version