主要用到Control.RenderControl 方法,该方法有两个重载版本:
下面是代码示例:
private void ToExcel(System.Web.UI.Control ctl,string filename)

...{
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(filename+".xls",System.Text.Encoding.UTF8));
HttpContext.Current.Response.Charset ="GB2312";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
Control.RenderControl (HtmlTextWriter) | |
Control.RenderControl (HtmlTextWriter, ControlAdapter) |
下面是代码示例:














根据代码中的注释可知,也可以导出为其它格式。要注意:该方法只用于导出控件呈现的内容而非数据集。