【发布时间】:2012-05-19 17:44:17
【问题描述】:
我无法将我即时创建的 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();
}
}
我有很多looked links - 但没有什么能很好地工作。我很多人使用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();
【问题讨论】:
-
怎么添加wordDocument.Save(); ?我试过了,唯一可能接近它的代码是 .Close() ,这对我不起作用。
标签: c# asp.net .net ms-word openxml