使用ASP.NET MVC 4在OpenXML SDK中流式传输Word文档会损坏文档

Ric*_*icL 0 asp.net-mvc ms-word openxml-sdk

我试图在ASP.NET MVC 4上执行此操作:

MemoryStream mem = new MemoryStream();
        using (WordprocessingDocument wordDoc =
            WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
        {
            // instantiate the members of the hierarchy
            Document doc = new Document();
            Body body = new Body();
            Paragraph para = new Paragraph();
            Run run = new Run();
            Text text = new Text() { Text = "The OpenXML SDK rocks!" };

            // put the hierarchy together
            run.Append(text);
            para.Append(run);
            body.Append(para);
            doc.Append(body);

            //wordDoc.Close();

            ///wordDoc.Save();
        }


return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");
Run Code Online (Sandbox Code Playgroud)

然而,ABC.docx打开已损坏,即使修复它也无法打开.

有任何想法吗?

链接的Qs:

使用OpenXML SDK w/ASP.NET流式传输内存Word文档导致"损坏"文档

Ric*_*icL 5

显然问题来自于缺少这2行:

wordDoc.AddMainDocumentPart();
wordDoc.MainDocumentPart.Document = doc;
Run Code Online (Sandbox Code Playgroud)

将代码更新到下面,它现在可以完美无缺地工作,即使没有任何额外的冲洗等也是必需的.

MemoryStream mem = new MemoryStream();
        using (WordprocessingDocument wordDoc =
            WordprocessingDocument.Create(mem, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
        {
            wordDoc.AddMainDocumentPart();
            // instantiate the members of the hierarchy
            Document doc = new Document();
            Body body = new Body();
            Paragraph para = new Paragraph();
            Run run = new Run();
            Text text = new Text() { Text = "The OpenXML SDK rocks!" };

            // put the hierarchy together
            run.Append(text);
            para.Append(run);
            body.Append(para);
            doc.Append(body);
            wordDoc.MainDocumentPart.Document = doc;
            wordDoc.Close();
        }
return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ABC.docx");
Run Code Online (Sandbox Code Playgroud)