OpenXml 创建word文档并下载

OpenXml create word document and download

我刚刚开始探索 OpenXml,我正在尝试创建一个新的简单 word 文档,然后下载该文件

这是我的代码

[HttpPost]
        public ActionResult WordExport()
        {
            var stream = new MemoryStream();
            WordprocessingDocument doc = WordprocessingDocument.Create(stream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true);

            MainDocumentPart mainPart = doc.AddMainDocumentPart();

            new Document(new Body()).Save(mainPart);

            Body body = mainPart.Document.Body;
            body.Append(new Paragraph(
                        new Run(
                            new Text("Hello World!"))));

            mainPart.Document.Save();


            return File(stream, "application/msword", "test.doc");


        }

我原以为它会包含 'Hello World!' 但是当我下载文件时,文件是空的

我错过了什么? 谢谢

您似乎有两个主要问题。首先,您需要在 WordprocessingDocument 上调用 Close 方法,以便保存某些文档部分。最干净的方法是在 WordprocessingDocument 周围使用 using 语句。这将导致为您调用 Close 方法。其次,你需要 Seekstream 的开头,否则你会得到一个空结果。

您的 OpenXml 文件的文件扩展名和内容类型也不正确,但这通常不会导致您遇到的问题。

完整的代码清单应该是:

var stream = new MemoryStream();
using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document, true))
{
    MainDocumentPart mainPart = doc.AddMainDocumentPart();

    new Document(new Body()).Save(mainPart);

    Body body = mainPart.Document.Body;
    body.Append(new Paragraph(
                new Run(
                    new Text("Hello World!"))));

    mainPart.Document.Save();

    //if you don't use the using you should close the WordprocessingDocument here
    //doc.Close();
}
stream.Seek(0, SeekOrigin.Begin);

return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "test.docx");

我认为你必须在 return 之前将流位置设置为 0,例如:

stream.Position = 0;
return File(stream, "application/msword", "test.doc");