简体   繁体   English

OpenXml创建word文档并下载

[英]OpenXml create word document and download

I'm just starting to explore OpenXml and I'm trying to create a new simple word document and then download the file 我刚刚开始探索OpenXml,我正在尝试创建一个新的简单word文档,然后下载该文件

Here's my code 这是我的代码

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


        }

I was expecting that it would contain 'Hello World!' 我原以为它会包含'Hello World!' But when I download the file, the file is empty 但是当我下载文件时,文件是空的

What am I missing? 我错过了什么? Tks TKS

You seem to have two main issues. 你似乎有两个主要问题。 Firstly, you need to call the Close method on the WordprocessingDocument in order for some of the document parts to get saved. 首先,您需要在WordprocessingDocument上调用Close方法,以便保存一些文档部分。 The cleanest way to do that is to use a using statement around the WordprocessingDocument . 最简单的方法是在WordprocessingDocument周围使用using语句。 This will cause the Close method to get called for you. 这将导致为您调用Close方法。 Secondly, you need to Seek to the beginning of the stream otherwise you'll get an empty result. 其次,你需要Seek stream的开头,否则你将获得一个空的结果。

You also have the incorrect file extension and content type for an OpenXml file but that won't typically cause you the problem you are seeing. 您还有一个OpenXml文件的文件扩展名和内容类型不正确,但这通常不会导致您遇到的问题。

The full code listing should be: 完整的代码清单应该是:

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

I think you have to set the stream position to 0 before return, like: 我想你必须在返回之前将流位置设置为0,如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM