首页
学习
活动
专区
工具
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

回答 7

Stack Overflow用户

回答已采纳

发布于 2012-05-20 03:51:35

使用CopyTo代替,在WriteTo中有一个bug,当目标流不支持一次性写入所有内容时,它会导致无法写入缓冲区的全部内容。

票数 8
EN

Stack Overflow用户

发布于 2013-09-26 17:30:10

作为.NET Framework3.5和更低版本的变体。这个版本的框架在类Stream中没有CopyTo方法。因此,方法WriteTo被替换为下面的代码:

代码语言:javascript
复制
byte[] arr = documentStream.ToArray();
fileStream.Write(arr, 0, arr.Length);

http://blogs.msdn.com/b/mcsuksoldev/archive/2010/04/09/creating-a-new-microsoft-word-document-from-a-template-using-openxml.aspx发现了一个示例

票数 3
EN

Stack Overflow用户

发布于 2012-05-20 05:27:11

我认为您的ContentType值不正确;这是Word 97 - 2003格式的值。将其更改为:

代码语言:javascript
复制
application/vnd.openxmlformats-officedocument.wordprocessingml.document

看看这是否能解决这个问题。

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

https://stackoverflow.com/questions/10667513

复制
相关文章

相似问题

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