ASP.NET导出页面内容至word文档

前台页面需要添加属性:EnableEventValidation="false"

导出事件主要代码:  

 protected void btnImportPage_Click(object sender, EventArgs e)
        {
            //设置Http的头信息,编码格式
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();

            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("行政管理制度.doc", System.Text.Encoding.UTF8));
            HttpContext.Current.Response.ContentType = "application/ms-word";

            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //关闭控件的视图状态
            Page.EnableViewState = false;
            //初始化HtmlWriter
            System.IO.StringWriter writer = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
            Page.RenderControl(htmlWriter);
            //输出
            string pageHtml = writer.ToString();
            int startIndex = pageHtml.IndexOf("<div style=\"margin: 0 auto;\" id=\"mainContent\">");
            int endIndex = pageHtml.LastIndexOf("</div>");
            int lenth = endIndex - startIndex;
            pageHtml = pageHtml.Substring(startIndex, lenth);
            pageHtml = pageHtml.Remove(pageHtml.LastIndexOf("<div class=\"flowbar\">"));
            //设置图片路径
            Uri MyUrl = Request.UrlReferrer;
            pageHtml = pageHtml.Replace("../Images/", "http://" + MyUrl.Authority + "/Images/").Replace("textarea", "span");   
            HttpContext.Current.Response.Write(pageHtml.ToString());
            HttpContext.Current.Response.End();
        }


评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悠悠虾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值