现在的位置: 首页 > 综合 > 正文

asp.net导出excel文件

2013年10月14日 ⁄ 综合 ⁄ 共 1096字 ⁄ 字号 评论关闭
 public class WebOffice
    {
        /// <summary>
        /// 将控件内容导出到Excel
        /// </summary>
        /// <param name="ctl"></param>
        public static void ControlToExcel(System.Web.UI.Control ctl,string fileName)
        {
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
            ctl.RenderControl(hw);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
            HttpContext.Current.Response.ContentType = "applicationnd.ms-excel";
            HttpContext.Current.Response.Charset = "";
            ctl.Page.EnableViewState = false;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName));
            HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=\"textml; charset=GB2312\"><title></title></head><body><center>");
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.Write("</center></body><ml>");
            HttpContext.Current.Response.End();
        }

        public static void ControlToExcel(System.Web.UI.Control ctl)
        {
            ControlToExcel(ctl, DateTime.Now.ToShortDateString() + ".xls");
        }
    }

抱歉!评论已关闭.