首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用ASP.NETSDKw/ OpenXML在内存中流式传输Word文档会导致文档“损坏”

使用ASP.NETSDKw/ OpenXML在内存中流式传输Word文档会导致文档“损坏”
EN

Stack Overflow用户
提问于 2012-05-20 01:44:17
回答 7查看 19.9K关注 0票数 20

我无法将我即时创建的word文档流式传输到浏览器。我经常收到来自Microsoft Word的消息,指出文档已损坏。

当我通过控制台应用程序运行代码并将ASP.NET排除在外时,文档可以正确生成,没有任何问题。我相信一切都围绕着把文件写下来。

下面是我的代码:

代码语言:javascript
复制
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();
    }
}

我在很多links上都有looked --但是没有一种是非常有效的。我有很多人使用MemoryStream.WriteTo,也有一些人使用BinaryWrite --在这一点上,我不确定正确的方式是什么。此外,我还尝试了较长的内容类型,即application/vnd.openxmlformats-officedocument.wordprocessingml.document,但没有成功。

一些屏幕截图-即使你试图恢复,你也会得到相同的“部件丢失或无效”。

为那些遇到这个问题的人提供的解决方案:

WordProcessingDocumentusing指令中,必须调用:

代码语言:javascript
复制
wordDocument.Save();

此外,要正确地流式传输MemoryStream,请在外部using块中使用以下代码:

代码语言:javascript
复制
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();

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10667513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档