简体   繁体   中英

Create a DocX and save to client machine c#

I am using the library from: https://github.com/xceedsoftware/DocX/blob/master/Xceed.Document.NET/Src/Document.cs in an MVC Project.

The functionality is now sitting on my server;

 public void Build(Results umbracoFormValues)
    {
        var ms = new MemoryStream();
        using (var document = DocX.Create(ms))
        {
            var heading = new Heading();
            heading.Branding(document);
            var sections = umbracoFormValues.SectionResults;
            foreach (var section in sections)
            {
                heading.Render(document, section);
                ConstructFieldTypes(document, section);
                new Footer().Render(document);
            }
            ms.Position = 0;
            document.SaveAs(new CreateNew().DocumentFileName(umbracoFormValues));
        }
    }

How do I then grab the newly created file and make it downloadable to the user/client?

Many thanks in advance.

You can change your Build method to return the stream:

public Stream Build(Results umbracoFormValues)
{
    var ms = new MemoryStream();
    //code omitted for simplicity
    return ms;
}

Then in your action:

public async Task<IActionResult> MyAction(Results umbracoFormValues)
{
    var stream = Build(umbracoFormValues);

    var mimeType = "application/vnd.openxmlformats-officedocument.wordprocessing";
    var fileName = "myReport.docx";

    return File(stream, mimeType, fileName);
}

Keep in mind that there may be some differences depending on the dotnet core/framework you're using, as you haven't specified that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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