欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET导出带格式的Word文档

程序员文章站 2022-03-30 21:57:21
可直接拷贝运行下面的代码测试 aspx 代码 <%@ page language="c#" autoeventwireup="true&qu...

可直接拷贝运行下面的代码测试
aspx 代码
<%@ 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="">
<head id="head1" runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <: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>

 

 

作者 孟宪会