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

本文介绍如何在前端页面上实现导出Word文档的功能,包括设置HTTP头信息、编码方式、内容类型、字符集等,并通过移除不必要的元素来优化HTML代码,最后输出并结束响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

导出事件主要代码:  

[csharp]  view plain copy print ?
  1. protected void btnImportPage_Click(object sender, EventArgs e)  
  2.        {  
  3.            //设置Http的头信息,编码格式  
  4.            HttpContext.Current.Response.Buffer = true;  
  5.            HttpContext.Current.Response.Clear();  
  6.            HttpContext.Current.Response.ClearContent();  
  7.            HttpContext.Current.Response.ClearHeaders();  
  8.   
  9.            HttpContext.Current.Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode("行政管理制度.doc", System.Text.Encoding.UTF8));  
  10.            HttpContext.Current.Response.ContentType = "application/ms-word";  
  11.   
  12.            HttpContext.Current.Response.Charset = "UTF-8";  
  13.            HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.UTF8;  
  14.            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;  
  15.            //关闭控件的视图状态  
  16.            Page.EnableViewState = false;  
  17.            //初始化HtmlWriter  
  18.            System.IO.StringWriter writer = new System.IO.StringWriter();  
  19.            System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);  
  20.            Page.RenderControl(htmlWriter);  
  21.            //输出  
  22.            string pageHtml = writer.ToString();  
  23.            int startIndex = pageHtml.IndexOf("<div style=\"margin: 0 auto;\" id=\"mainContent\">");  
  24.            int endIndex = pageHtml.LastIndexOf("</div>");  
  25.            int lenth = endIndex - startIndex;  
  26.            pageHtml = pageHtml.Substring(startIndex, lenth);  
  27.            pageHtml = pageHtml.Remove(pageHtml.LastIndexOf("<div class=\"flowbar\">"));  
  28.            //设置图片路径  
  29.            Uri MyUrl = Request.UrlReferrer;  
  30.            pageHtml = pageHtml.Replace("../Images/""http://" + MyUrl.Authority + "/Images/").Replace("textarea""span");     
  31.            HttpContext.Current.Response.Write(pageHtml.ToString());  
  32.            HttpContext.Current.Response.End();  
  33.        }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值