Export GridView data to CSV file
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SearchResults.csv");
Response.Charset = "";
Response.ContentType = "application/text";
gvSearchResutls.AllowPaging = false;
//Bind DataTable to GridView
//Search() method returns a DataTable of search results
gvSearchResutls.DataSource = Search();
gvSearchResutls.DataBind();
//String builder class to add row data
StringBuilder sb = new StringBuilder();
for (int k = 0; k < gvSearchResutls.Columns.Count; k++)
{
//add separator
sb.Append(gvSearchResutls.Columns[k].HeaderText + ',');
}
append new line
sb.Append("\r\n");
Get Rows
for (int i = 0; i < gvSearchResutls.Rows.Count; i++)
{
//Get columns
for (int k = 0; k < gvSearchResutls.Columns.Count; k++)
{
//add separator
sb.Append(gvSearchResutls.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
References:
http://www.victorchen.info/export-datatable-to-csv-file-download-in-c/