Export Gridview to CSV Format

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