Thursday, March 3, 2011

How to export gridview content to csv in asp.net C#?

Here I'm showing you how to export a GridView content to csv (Comma separated values) in asp.net using C#.

So here I have a GridView gvResult and a button btnExportToCsv . On btnExportToCsv click we want to export gvResults data to export in csv file. So here is the code bellow hope this helps you.

protected void btnExportToCsv_Click(object sender, EventArgs e)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.csv");
Response.Charset = string.Empty;
Response.ContentType = "application/text";
gvResult.AllowPaging = false;
gvResult.DataBind();
StringBuilder sb = new StringBuilder();
string coloumns = string.Empty;
for (int k = 1; k < gvResult.Columns.Count - 1; k++)
{
//add ',' separator

coloumns += gvResult.Columns[k].HeaderText + ',';
sb.Append(gvResult.Columns[k].HeaderText + ',');

}

//This portion is to replace the header text of the gvResult to the binding data source data table's columns //name so can we get the correct data from the datasource ,because we formated the gvResult header as per //our reqirement and the header text doesn't match with the datasource table
coloumns = coloumns.Replace("Coupon ID", "ID_Coupon");
coloumns = coloumns.Replace("Employee ID", "Customer_ID");
coloumns = coloumns.Replace("Created On", "CreatedDate");
coloumns = coloumns.Replace("Valid Until", "ValidUntil");
coloumns = coloumns.Replace("Activated", "ActivatedDate");
coloumns = coloumns.Replace("Cashed", "CashedDate");
coloumns = coloumns.Replace("Euro", "EuroValue");
//here we remove the last ',' from the string 'coloumns'

coloumns = string.IsNullOrEmpty(coloumns) ? string.Empty : coloumns.Substring(0, coloumns.LastIndexOf(","));
string[] clmnList = coloumns.Split(',');
DataTable dt = new DataTable();

//Here takes the required fields from the gridview(gvResult's datasource)
dt = gvResult.DefaultView.ToTable(false, clmnList.ToArray());
//append new line
sb.Append("\r\n");

//Here put the data to the particular column
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(Convert.ToString(dt.Rows[i][k]) + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
catch (Exception ex) { }
}

Hope this will help!

No comments:

Post a Comment