在MS Word文件(.docx)上呈现HTML代码 - 文件已损坏

时间:2016-11-18 11:36:03

标签: html ms-word

以下是代码。我们需要做些什么改变。

HttpContext context = HttpContext.Current;
    context.Response.Clear();
    context.Response.AppendHeader("content-disposition", "attachment;filename=" + strFileName + ".docx");
    context.Response.Charset = "";
    context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    var stringWriter = new StringWriter();
    stringWriter.Write(strContent);
    var htmlWriter = new HtmlTextWriter(stringWriter);
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
    HttpContext.Current.Response.Write(oHtmlTextWriter);
    context.Response.Write(stringWriter.ToString());
    context.Response.End();

1 个答案:

答案 0 :(得分:1)

您不能简单地写出HTML,为其提供.docx文件扩展名,并期望Word正确打开该文档。 .docx文件需要是一个有效的Office Open XML包,它基本上是一个包含各种XML文件的zip容器(您可以通过将.docx文档重命名为.zip然后使用标准zip工具打开它来轻松看到它)。

您现在可以采取哪些措施来解决问题并获取有效的Word文件:

  • 使用Microsoft的Open XML SDK创建有效的docx文件,而不是HTML。 SDK中包含一些示例,向您展示如何使用它创建Word文档。
  • 如果您无法通过创建HTML进行更改,则还可以使用所谓的altChunk将HTML嵌入到Word文档中。这在另一个答案here中进行了描述。
  • 根据您生成的内容,可能还可以创建模板Word文档,您只需要填充占位符。这种解决方案可以是围绕内容控件和自定义XML构建。然后,您只需要替换docx包中的单个XML文件来填充文档。有一个基本的教程here