OpenXml create word document and download

2020-07-11 09:19发布

I'm just starting to explore OpenXml and I'm trying to create a new simple word document and then download the file

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!' But when I download the file, the file is empty

What am I missing? Tks

2条回答
一夜七次
2楼-- · 2020-07-11 09:59

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. The cleanest way to do that is to use a using statement around the WordprocessingDocument. This will cause the Close method to get called for you. Secondly, you need to Seek to the beginning of the stream otherwise you'll get an empty result.

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.

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");
查看更多
Lonely孤独者°
3楼-- · 2020-07-11 10:01

I think you have to set the stream position to 0 before return, like:

stream.Position = 0;
return File(stream, "application/msword", "test.doc");
查看更多
登录 后发表回答