0

我正在尝试在 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 打开时已损坏,即使修复后也无法打开。

有任何想法吗?

链接问题:

使用带有 ASP.NET 的 OpenXML SDK 在内存 Word 文档中流式传输会导致“损坏”文档

4

1 回答 1

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");
于 2012-12-14T07:24:09.093 回答