欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#导出文本内容到word文档的方法

时间:2021-03-01 13:44:03|栏目:.NET代码|点击:

本文实例讲述了C#导出文本内容到word文档的方法。分享给大家供大家参考。具体实现方法如下:

<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server">
 protected void Page_Load(object sender, EventArgs e)
 {
  Repeater1.DataSource = new String[] { "测", "孟宪会" };
  Repeater1.DataBind();
 }
 protected void Button1_Click(object sender, EventArgs e)
 {
  String ExportFileName = "孟宪会导出 Word 测试";
  if (Request.Browser.Browser.IndexOf("MSIE") > -1)
  {
   ExportFileName = HttpUtility.UrlEncode(ExportFileName, System.Text.UnicodeEncoding.GetEncoding("GB2312"));
  }
  ExportFileName += ".doc";
  Response.Clear();
  Response.BufferOutput = true;
  Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  Response.Charset = "GB2312";
  Response.AppendHeader("Content-Disposition", "attachment;filename=" + ExportFileName);
  Response.ContentType = "application/ms-word";
  Page.EnableViewState = false;
  System.IO.StringWriter stringWriter = new System.IO.StringWriter();
  HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
  Literal header = new Literal();
  header.Text = "<h2>文章标题</h2>";
  Header.Controls.Add(header);
  Header.RenderControl(textWriter);
  this.Repeater1.RenderControl(textWriter);
  Response.Write("<html xmlns:v='urn:schemas-microsoft-com:vml' xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns:m='http://schemas.microsoft.com/office/2004/12/omml' xmlns='http://www.w3.org/TR/REC-html40'><head></head><body lang=ZH-CN>" + stringWriter.ToString());
  Response.End();
  Response.Flush();
 }
 public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
 {
 }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <asp:Repeater ID="Repeater1" runat="server">
  <HeaderTemplate>
   <table cellspacing="1" cellpadding="3" width="96%" align="center" border="1">
  </HeaderTemplate>
  <FooterTemplate>
   </table></FooterTemplate>
  <ItemTemplate>
   <tr><td>测试啦</td><td>This is a 测试啊</td><td>
    <%#Container.DataItem%></td></tr>
  </ItemTemplate>
 </asp:Repeater>
 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出成Word文档" />
 </form>
</body>
</html>

希望本文所述对大家的C#程序设计有所帮助。

上一篇:C# 利用StringBuilder提升字符串拼接性能的小例子

栏    目:.NET代码

下一篇:MVC+EasyUI+三层新闻网站建立 验证码生成(三)

本文标题:C#导出文本内容到word文档的方法

本文地址:http://www.codeinn.net/misctech/72243.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有