尝试使用OpenXml创建内存中的Word文档时表示';他腐败了

本文关键字:表示 文档 Word OpenXml 创建 内存 | 更新日期: 2023-09-27 18:29:57

我构建了一个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#从OpenXML返回内存流,导致损坏的单词文件

使用OpenXML SDK w/ASP.NET对内存中的Word文档进行流式处理;腐败;文档

尝试使用OpenXml创建内存中的Word文档时表示';他腐败了

ms.GetBuffer()将返回自动管理和调整大小的缓冲区。这将从您写入的数据开始,但在最后可能包含额外的'0字节,以防您继续使用.Write()

要返回MemoryStream,您可以使用以下任一项:

ms.Position = 0;
ms.CopyTo(curContext.Response.OutputStream);

或:

var msResult = ms.ToArray();
curContext.Response.OutputStream.Write(msResult, 0, msResult.Length);

您可以创建这样的方法来处理内存流和格式化的文件名

private static void DynaGenWordDoc(string fileName, Page page, WordprocessingDocument wdoc)
{
    page.Response.ClearContent();
    page.Response.ClearHeaders();
    page.Response.ContentType = "application/vnd.ms-word";
    page.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.docx", fileName));
    using (MemoryStream memoryStream = new MemoryStream())
    {
        wdoc.SaveAs(memoryStream);
        memoryStream.WriteTo(page.Response.OutputStream);
        memoryStream.Close();
    }
    page.Response.Flush();
    page.Response.End();
}