使用OpenXML SDK w/ASP.NET流式传输内存Word文档导致"损坏"文档

kd7*_*kd7 18 .net c# asp.net ms-word openxml

我无法将我创建的word文档流式传输到浏览器.我不断收到来自Microsoft Word的消息,该文档已损坏.

当我通过控制台应用程序运行代码并将ASP.NET从图片中删除时,文档生成正确,没有任何问题.我相信一切都围绕着写下文件.

这是我的代码:

using (MemoryStream mem = new MemoryStream())
{
    // Create Document
    using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document, true))
    {
        // Add a main document part. 
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

        new Document(new Body()).Save(mainPart);

        Body body = mainPart.Document.Body;
        body.Append(new Paragraph(new Run(new Text("Hello World!"))));

        mainPart.Document.Save();
        // Stream it down to the browser

        // THIS IS PROBABLY THE CRUX OF THE MATTER <---
        Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
        Response.ContentType = "application/vnd.ms-word.document";
        mem.WriteTo(Response.OutputStream);
        Response.End();
    }
}
Run Code Online (Sandbox Code Playgroud)

看了很多链接 - 但没有什么可行的.我很多人使用MemoryStream.WriteTo和使用BinaryWrite- 在这一点上我不确定正确的方法是什么.我也试过更长的内容类型,application/vnd.openxmlformats-officedocument.wordprocessingml.document但没有运气.

一些截图 - 即使你试图恢复你得到相同的"部分丢失或无效"

那些偶然发现这个问题的人的解决方案:

using指令中WordProcessingDocument,您必须致电:

wordDocument.Save();
Run Code Online (Sandbox Code Playgroud)

另外要正确地流式传输MemoryStream,请在外部使用块中使用它:

Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AppendHeader("Content-Disposition", "attachment;filename=HelloWorld.docx");
mem.Position = 0;
mem.CopyTo(Response.OutputStream);
Response.Flush();
Response.End();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述

Mag*_*nus 7

CopyTo相反,使用的错误是WriteTo当目标流不支持一次编写所有内容时,它无法编写缓冲区的整个内容.