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

时间:2012-12-14 03:34:50

标签: 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");

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

有什么想法吗?

链接Qs:

Streaming In Memory Word Document using OpenXML SDK w/ASP.NET results in "corrupt" document

1 个答案:

答案 0 :(得分:5)

显然问题来自错过这2行:

wordDoc.AddMainDocumentPart();
wordDoc.MainDocumentPart.Document = doc;

将代码更新到下面,它现在可以完美运行,即使没有任何额外的冲洗等也是必需的。

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");