【发布时间】:2016-01-12 18:51:48
【问题描述】:
我已经构建了一个 ActionResult 来将数据输出到 Word 文档。我在编译或运行时没有收到任何错误,但在尝试打开文件时我收到消息:'很抱歉,我们无法打开 filename.docx,因为我们发现其内容有问题。'。
这是我想要做的:
public override void ExecuteResult(ControllerContext context)
{
//Create a response stream to create and write the Excel file
HttpContext curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=text.docx");
curContext.Response.Charset = "";
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
curContext.Response.ContentType = "application/vnd.ms-word";
//Write the stream back to the response
var ms = new MemoryStream();
var repData = "<b>Mark's Test Book: With a Special Sub Title</b><br /><br /><b>Chapter: Chapter Title 1: Chapter Title sub</b><br /><br />";
Document.CreateAndAddHtmlToWordprocessingStream(ms, repData);
curContext.Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
curContext.Response.End();
}
静态方法如下:
public static void CreateAndAddHtmlToWordprocessingStream(Stream stream, string inputBody)
{
// Open a WordProcessingDocument based on a stream.
WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document);
// Add a main document part.
MainDocumentPart mainPart = wordprocessingDocument.AddMainDocumentPart();
// Create the document structure.
mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
// Create the document body.
mainPart.Document.AppendChild(new Body());
var ms = new MemoryStream(System.Text.Encoding.Default.GetBytes("<html><head></head><body style=\"font-family:'Calibri';\">" + inputBody + "</body></html>"));
var altChunkId = "id";
var formatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, altChunkId);
formatImportPart.FeedData(ms);
var altChunk = new AltChunk { Id = altChunkId };
mainPart.Document.Body.Append(altChunk);
mainPart.Document.Save();
// Close the document handle.
wordprocessingDocument.Close();
// Caller must close the stream.
}
我看过这两个帖子,但没有找到任何帮助:
C# return memory stream from OpenXML resulting to a corrupted word file
Streaming In Memory Word Document using OpenXML SDK w/ASP.NET results in "corrupt" document
【问题讨论】:
-
ms.GetBuffer()听起来不对...通常你会做ms.Position = 0;并返回流。如果要先命中字节数组,请使用ms.ToArray()。