How to Export Gridview in CSV

  1. Response.Clear();  
  2.    Response.Buffer = true;  
  3.    Response.AddHeader("content-disposition",  
  4.     "attachment;filename=GridViewExport.csv");  
  5.    Response.Charset = "";  
  6.    Response.ContentType = "application/text";  
  7.   
  8.    GridView1.AllowPaging = false;  
  9.    GridView1.DataBind();  
  10.   
  11.    StringBuilder sb = new StringBuilder();  
  12.    for (int k = 0; k < GridView1.Columns.Count; k++)  
  13.    {  
  14.        //add separator  
  15.        sb.Append(GridView1.Columns[k].HeaderText + ',');  
  16.    }  
  17.    //append new line  
  18.    sb.Append("\r\n");  
  19.    for (int i = 0; i < GridView1.Rows.Count; i++)  
  20.    {  
  21.        for (int k = 0; k < GridView1.Columns.Count; k++)  
  22.        {  
  23.            //add separator  
  24.            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');  
  25.        }  
  26.        //append new line  
  27.        sb.Append("\r\n");  
  28.    }  
  29.    Response.Output.Write(sb.ToString());  
  30.    Response.Flush();  
  31.    Response.End();