OpenXml创建word文档并下载

时间:2016-03-29 11:51:31

标签: c# asp.net-mvc openxml

我刚刚开始探索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!' 但是当我下载文件时,文件是空的

我错过了什么? TKS

2 个答案:

答案 0 :(得分:7)

您似乎有两个主要问题。首先,您需要调用Close上的WordprocessingDocument方法,以便保存部分文档部分。最简单的方法是在using周围使用WordprocessingDocument语句。这将导致为您调用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");

答案 1 :(得分:0)

我认为你必须在返回前将流位置设置为0,如:

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