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
You seem to have two main issues. Firstly, you need to call the
Close
method on theWordprocessingDocument
in order for some of the document parts to get saved. The cleanest way to do that is to use ausing
statement around theWordprocessingDocument
. This will cause theClose
method to get called for you. Secondly, you need toSeek
to the beginning of thestream
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:
I think you have to set the stream position to 0 before return, like: