您的位置:首页 > 其它

下载DataGrid内容,作为Excel可打开的文件

2006-09-10 18:46 543 查看
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AIS.Web
{
/// <summary>
/// 把GridView作为文件下载,可供Excel打开
/// </summary>
public class DataGridToFile
{
public DataGridToFile()
{}

public static void Download(DataGrid dg)
{
Download(dg, "report_" + DateTime.Now.ToString("yyyyMMdd") +".xls" );
}

public static void Download(DataGrid dg, string fileName)
{
TranComplexCtlToLiteral(dg);

System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw=new HtmlTextWriter(sw);
dg.RenderControl(htw);

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer=false;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename="+fileName);
HttpContext.Current.Response.ContentType = "application/excel";
HttpContext.Current.Response.Charset="GB2312";
HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}

/// <summary>
/// 把复杂控件都变为只显示文字的控件
/// </summary>
private static void TranComplexCtlToLiteral(WebControl ctl)
{
if(ctl==null) return;
if(ctl.HasControls()==false) return;

for(int i =0; i < ctl.Controls.Count; i++)
{
Literal l=new Literal();
WebControl curChild=ctl.Controls[i] as WebControl;

if(curChild is HyperLink)
{
HyperLink hl=curChild as HyperLink;
l.Text = hl.Text;
ctl.Controls.Remove(curChild);
ctl.Controls.AddAt(i,l);
}
else if(curChild is DropDownList)
{
DropDownList ddl=curChild as DropDownList;
l.Text=ddl.SelectedItem.Text;
ctl.Controls.Remove(curChild);
ctl.Controls.AddAt(i,l);
}
TranComplexCtlToLiteral(curChild);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: