punkouter
punkouter

Reputation: 5366

How do I return a MVC ActionResult of a OPENXML Word document ?

I have basic code that creates the file in a console (See below).. But I am writing a MVC app so I need to return that XML document as an ActionResult.... Ive been searching the web 2 hours looking for a simple example with no luck..

What do I add to this to make it a ActionResult ?

       string filePath = @"C:\temp\OpenXMLTest.docx";
        using (WordprocessingDocument doc = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
        {
            //// Creates the MainDocumentPart and add it to the document (doc)     
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document(
                new Body(
                    new Paragraph(
                        new Run(
                            new Text("Hello World!!!!!")))));
        }

Upvotes: 2

Views: 4839

Answers (1)

mcdonams
mcdonams

Reputation: 211

Here's some sample code. Note this code doesn't load the file from disk, it creates the file on-the-fly and writes to a MemoryStream. The changes needed to write to disk are minimal.

    public ActionResult DownloadDocx()
    {
        MemoryStream ms;

        using (ms = new MemoryStream())
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
            {
                MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

                mainPart.Document = new Document(
                    new Body(
                        new Paragraph(
                            new Run(
                                new Text("Hello world!")))));
            }
        }

        return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Test.docx");
    }

Upvotes: 5

Related Questions