Monday, 2 January 2017

Gridview Excel Export In C#

  1. void             BindGrid()  
  2. {  
  3.   
  4.  DataSet objds = "";  
  5.            GridView1.DataSource = objds;  
  6.             GridView1.DataBind();  
  7. }  
  8.   
  9. void ExcelExport  
  10. {  
  11.             Response.ClearContent();  
  12.             Response.Buffer = true;  
  13.             Response.AddHeader("content-disposition"string.Format("attachment; filename={0}""UserDetails.xls"));  
  14.             Response.ContentType = "application/ms-excel";  
  15.             StringWriter sw = new StringWriter();  
  16.             HtmlTextWriter htw = new HtmlTextWriter(sw);  
  17.             gvAdminDetails.AllowPaging = false;  
  18.             BindGrid();  
  19.             //Change the Header Row back to white color  
  20.             Gridview1.HeaderRow.Style.Add("background-color""#FFFFFF");  
  21.               
  22.             //Applying stlye to gridview header cells  
  23.             for (int i = 0; i < gvAdminDetails.HeaderRow.Cells.Count; i++)  
  24.             {  
  25.                Gridview1.HeaderRow.Cells[i].Style.Add("background-color""#F0F0F0");  
  26.             }  
  27.             int j = 1;  
  28.             //This loop is used to apply stlye to cells based on particular row  
  29.             foreach (GridViewRow gvrow in gvAdminDetails.Rows)  
  30.             {  
  31.                 gvrow.BackColor = System.Drawing.Color.White;  
  32.                 if (j <= Gridview1.Rows.Count)  
  33.                 {  
  34.                     if (j % 2 != 0)  
  35.                     {  
  36.                         for (int k = 0; k < gvrow.Cells.Count; k++)  
  37.                         {  
  38.                             gvrow.Cells[k].Style.Add("background-color""#F0F0F0");  
  39.                         }  
  40.                     }  
  41.                 }  
  42.                 j++;  
  43.             }  
  44.   
  45.            Gridview1.RenderControl(htw);  
  46.             Response.Write(sw.ToString());  
  47.              
  48.            Gridview1.AllowPaging = true;  
  49.             Response.End();  
  50. }  
  51.   
  52.    
  53. public override void VerifyRenderingInServerForm(Control control)  
  54.     {  
  55.         //required to avoid the runtime error "  
  56.       //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."  
  57.     }  

No comments:

Post a Comment

Search text in stored procedure in SQL Server

SELECT *   FROM   sys.procedures WHERE  Object_definition(object_id) LIKE '%keyword%'