Export Grid Data To Excel

C# Code
  1. protected void ExportToExcel(object sender, EventArgs e)  
  2. {  
  3.     Response.Clear();  
  4.     Response.Buffer = true;  
  5.     Response.AddHeader("content-disposition""attachment;filename=FileName.xls");  
  6.     Response.Charset = "";  
  7.     Response.ContentType = "application/vnd.ms-excel";  
  8.     using (StringWriter sw = new StringWriter())  
  9.     {  
  10.         HtmlTextWriter hw = new HtmlTextWriter(sw);  
  11.   
  12.         //To Export all pages  
  13.         gridView1.AllowPaging = false;  
  14.         this.BindGrid();  //Your Method to bind GridView
  15.   
  16.         gridView1.HeaderRow.BackColor = Color.White;  
  17.         foreach (TableCell cell in gridView1.HeaderRow.Cells)  
  18.         {  
  19.             cell.BackColor = gridView1.HeaderStyle.BackColor;  
  20.         }  
  21.         foreach (GridViewRow row in gridView1.Rows)  
  22.         {  
  23.             row.BackColor = Color.White;  
  24.             foreach (TableCell cell in row.Cells)  
  25.             {  
  26.                 if (row.RowIndex % 2 == 0)  
  27.                 {  
  28.                     cell.BackColor = gridView1.AlternatingRowStyle.BackColor;  
  29.                 }  
  30.                 else  
  31.                 {  
  32.                     cell.BackColor = gridView1.RowStyle.BackColor;  
  33.                 }  
  34.                 cell.CssClass = "textmode";  
  35.             }  
  36.         }  
  37.   
  38.         gridView1.RenderControl(hw);  
  39.   
  40.         //style to format numbers to string  
  41.         string style = @"<style> .textmode { } </style>";  
  42.         Response.Write(style);  
  43.         Response.Output.Write(sw.ToString());  
  44.         Response.Flush();  
  45.         Response.End();  
  46.     }  
  47. }