Home
Manage Your Code
Snippet: asp net exel sheet from grid (C#)
Title: asp net exel sheet from grid Language: C#
Description: create exel sheet from grid contents Views: 516
Author: John Mc Morrin Date Added: 9/3/2010
Copy Code  
1
2
3protected void btnExportExcel_Click(object sender, EventArgs e)
4{
5	Response.Clear();
6	Response.Buffer = true;
7	Response.AddHeader("content-disposition","attachment;filename=GridViewExport.xls");
8	Response.Charset = "";
9	Response.ContentType = "application/vnd.ms-excel";
10	StringWriter sw = new StringWriter();
11	HtmlTextWriter hw = new HtmlTextWriter(sw);
12
13	GridView1.AllowPaging = false;
14	GridView1.DataBind();
15	//Change the Header Row back to white color
16	GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
17	//Apply style to Individual Cells
18	GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
19	GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
20	GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
21	GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");  
22	
23	for (int i = 0; i < GridView1.Rows.Count;i++ )
24	{
25	    GridViewRow row = GridView1.Rows[i];
26	    //Change Color back to white
27	    row.BackColor = System.Drawing.Color.White;
28	    //Apply text style to each Row
29	    row.Attributes.Add("class", "textmode");
30	    //Apply style to Individual Cells of Alternating Row
31	    if (i % 2 != 0)
32	    {
33	        row.Cells[0].Style.Add("background-color", "#C2D69B");
34	        row.Cells[1].Style.Add("background-color", "#C2D69B");
35	        row.Cells[2].Style.Add("background-color", "#C2D69B");
36	        row.Cells[3].Style.Add("background-color", "#C2D69B");  
37	    }
38	}
39	GridView1.RenderControl(hw);
40	//style to format numbers to string
41	string style = @"<style> .textmode { mso-number-format:\@; } </style>";
42	Response.Write(style);
43	Response.Output.Write(sw.ToString());
44	Response.Flush();
45	Response.End();
46}
47