Web控件导出至Excel/Word
#region Web控件导出至Excel/Word
/// <summary>
/// Web控件导出至Excel
/// </summary>
/// <param name="ctl">Web控件</param>
/// <param name="FileName">文件名</param>
public static void ToExcel(GridView ctl, string FileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(FileName)) + ".xls");
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
HttpContext.Current.Response.ContentType = "application/vnd.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
/// <summary>
/// Web控件导出至Word
/// </summary>
/// <param name="ctl">Web控件</param>
/// <param name="FileName">文件名</param>
public static void ToWord(System.Web.UI.Control ctl, string FileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(FileName)) + ".doc");
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
HttpContext.Current.Response.ContentType = "application/vnd.doc";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
#endregion