Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 581
DJPB Avatar asked Mar 29 '16 11:03

DJPB


1 Answers

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");
like image 192
petelids Avatar answered Sep 20 '22 05:09

petelids