关闭

WebControl(DataGrid/GridView)导出Excel、Word

标签: excelstring
277人阅读 评论(0) 收藏 举报
分类:

       /// <summary>
        ///
        /// </summary>
        /// <param name="dg"></param>
        /// <param name="name"></param>
        /// <param name="bm">编码</param>
        public static void OutExcel(System.Web.UI.Control dg, string name, string bm)
        {
            HttpResponse rsp = HttpContext.Current.Response;
            dg.Visible = true;
            rsp.Clear();
            rsp.Buffer = true;
            rsp.Charset = bm;
            name = "attachment;filename=" +HttpUtility.UrlPathEncode(name)+".xls";
            rsp.AppendHeader("Content-Disposition", name);
            rsp.ContentEncoding = System.Text.Encoding.GetEncoding(bm);
            rsp.ContentType = "application/ms-excel";
            dg.EnableViewState = false;
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            Page page = new Page();
            page.EnableEventValidation = false;
            page.DesignerInitialize();
            HtmlForm form = new HtmlForm();
            page.Controls.Add(form);
            form.Controls.Add(dg);

            page.RenderControl(oHtmlTextWriter);
            rsp.Write(oStringWriter.ToString());
            rsp.End();
        }

        public static void OutWord(System.Web.UI.WebControls.WebControl dg, string name)
        {
            HttpResponse rsp = HttpContext.Current.Response;
            dg.Visible = true;
            rsp.Clear();
            rsp.Buffer = true;
            rsp.Charset = "utf-8";
            name = "attachment;filename=" + name;
            rsp.AppendHeader("Content-Disposition", name);
            rsp.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            rsp.ContentType = "application/ms-word";
            dg.EnableViewState = false;
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            Page page = new Page();
            page.EnableEventValidation = false;
            page.DesignerInitialize();
            HtmlForm form = new HtmlForm();
            page.Controls.Add(form);
            form.Controls.Add(dg);

            form.RenderControl(oHtmlTextWriter);
            rsp.Write(oStringWriter.ToString());
            rsp.End();
        }

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:201126次
    • 积分:3467
    • 等级:
    • 排名:第9572名
    • 原创:152篇
    • 转载:29篇
    • 译文:0篇
    • 评论:17条
    文章分类
    最新评论