Code snippet of the day : Exporting DataGrid Data to Excel...

    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}

转载于:https://www.cnblogs.com/fengzhimei/archive/2004/06/18/16977.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值