Fengzhimei@Dot.Net
Designing My Colorful Dream
    Sometimes our clients maybe have such demand it is load the datagrid data(eg.address book) into an excel spreadsheet. There are several ways to accomplish this, However there is a simple, effective way to do this. 
    Here's the code:
1public static void DataGridToExcel(DataGrid dgExport,HttpResponse response)
2{
3 // clean up the response.object
4 response.Clear();
5 response.Charset = "";
6
7 // set the response mime type for excel
8 response.ContentType = "application/vnd.ms-excel";
9
10 // create a string writer
11 System.IO.StringWriter stringWrite = new System.IO.StringWriter();
12 // create an htmltextwriter which uses the stringwriter
13 HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
14  
15 // instantiate a datagrid
16 DataGrid dg = new DataGrid();
17 // just set the input datagrid = to the new dg grid
18 dg = dgExport;
19  
20 // I want to make sure there are no annoying gridlines
21 dg.GridLines = GridLines.None;
22 // Make the header text bold
23 dg.HeaderStyle.Font.Bold = true;
24  
25 // If needed, here's how to change colors/formatting at the component level
26 // dg.HeaderStyle.ForeColor = System.Drawing.Color.Black
27 // dg.ItemStyle.ForeColor = System.Drawing.Color.Black
28  
29 // bind the modified datagrid
30 dg.DataBind();
31 // tell the datagrid to render itself to our htmltextwriter
32 dg.RenderControl(htmlWrite);
33
34 //output the html
35 response.Write(stringWrite.ToString());
36 response.End();
37}
posted on 2004-06-18 18:13  fengzhimei  阅读(2234)  评论(2编辑  收藏  举报