我无法将我即时创建的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();
}
}
我在很多links上都有looked --但是没有一种是非常有效的。我有很多人使用MemoryStream.WriteTo
,也有一些人使用BinaryWrite
--在这一点上,我不确定正确的方式是什么。此外,我还尝试了较长的内容类型,即application/vnd.openxmlformats-officedocument.wordprocessingml.document
,但没有成功。
一些屏幕截图-即使你试图恢复,你也会得到相同的“部件丢失或无效”。
为那些遇到这个问题的人提供的解决方案:
在WordProcessingDocument
的using
指令中,必须调用:
wordDocument.Save();
此外,要正确地流式传输MemoryStream
,请在外部using块中使用以下代码:
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();
https://stackoverflow.com/questions/10667513
复制相似问题