【问题标题】:Serving a word document generated using Open XML from an asp.net webpage从 asp.net 网页提供使用 Open XML 生成的 word 文档
【发布时间】:2011-07-11 19:57:34
【问题描述】:

我正在尝试使用以下代码从 asp.net 页面提供 word 文档 (docx)

    protected void Page_Load(object sender, EventArgs e)
    {

        MemoryStream document = new MemoryStream();
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(document, WordprocessingDocumentType.Document))
        {
            MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
            SetMainDocumentContent(mainPart);
        }

        string fileName = "MsWordSample.docx";
        Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.OutputStream.Write(document.ToArray(), 0, document.ToArray().Length);
    }

    public static void SetMainDocumentContent(MainDocumentPart part)
    {
        const string docXml =
         @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> 
        <w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
        <w:body>
            <w:p>
                <w:r>
                    <w:t>Hello world!</w:t>
                </w:r>
            </w:p>
        </w:body>
        </w:document>";

        using (Stream stream = part.GetStream())
        {
            byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
            stream.Write(buf, 0, buf.Length);
        }
    }

但我在尝试打开文件时收到以下消息:“文件 {file name} 无法打开,因为内容存在问题”

然后我可以选择恢复实际修复文档的文档。

我是否遗漏了什么?

【问题讨论】:

  • Response.End() 修复了我的相同问题。谢谢@Fikre

标签: asp.net openxml


【解决方案1】:

您收到的错误消息意味着底层 XML 在某些方面不符合架构。这可能是由于元素顺序错误、忘记元素的父元素、添加错误属性、忘记必需元素等造成的。我建议下载Open XML SDK 2.0 Productivity Tool,创建一个测试文件,然后打开它查看XML 应该是什么。然后将该文件与您正在创建的文件进行比较,看看缺少什么。

【讨论】:

  • 另一个有用的工具是OpenXmlValidator。它将向您显示 XML 结构中的所有错误。对我的发展有巨大帮助。
  • 你说得对,无效XML的原因是我忘记添加Response.End()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
相关资源
最近更新 更多