C # MVC 4: create a Word document and download without saving to disk

This probably has a very simple answer, but I just can't find it.

I have a project using C # MVC 4 using Microsoft.Office.Interop.Word 12

In action, I try to dynamically create a Word file (using the database for information), and then I want to download it. The file does not exist (it was created from scratch), and I do not want to save it to disk (it does not need to be saved, because its contents are dynamic).

This is the code at the moment:

public ActionResult Generar(Documento documento) { Application word = new Application(); word.Visible = false; object miss = System.Reflection.Missing.Value; Document doc = word.Documents.Add(ref miss, ref miss, ref miss, ref miss); Paragraph par = doc.Content.Paragraphs.Add(ref miss); object style = "Heading 1"; par.Range.set_Style(ref style); par.Range.Text = "This is a dummy test"; byte[] bytes = null; // This is the part i need to get the bytes of the doc object doc.Close(); word.Quit(); return File(bytes, "application/octet-stream", "NewFile.docx"); } 
+4
source share
1 answer

Using the library that Robert Harvey recommended DocX.dll (thanks, gentleman), this would be a solution:

 using Novacode; using System.Drawing; . . . public ActionResult Generar(Documento documento) { MemoryStream stream = new MemoryStream(); DocX doc = DocX.Create(stream); Paragraph par = doc.InsertParagraph(); par.Append("This is a dummy test").Font(new FontFamily("Times New Roman")).FontSize(32).Color(Color.Blue).Bold(); doc.Save(); return File(stream.ToArray(), "application/octet-stream", "FileName.docx"); } 

I could not find a solution using Microsoft.Office.Interop.Word (something so simple, I am disappointed).

Thanks again to Robert and hope this example helps you solve the problem.

+7
source

Source: https://habr.com/ru/post/1482219/


All Articles