Generate a Word document in ASP.NET
John Reilly
March 19, 2024
Generating a Word document in the context of an ASP.NET controller is quite simple to do. However, it took me a little experimentation to work out just what was required. This post documents (pun very much intended) what we need to do.
Open XML
To generate a Word document in .NET, the most straightforward way is to use the Open XML library. We can install the library using the following command:
Generating a Word document in an ASP.NET controller
With the Open XML library installed, we can create a new Word document in the context of an ASP.NET controller. The following code demonstrates how to do this:
In this example, the GetWordDocument method creates a new Word document and adds the text "Hello, World!" to it. If we navigate to the /api/generate-word-document endpoint, we will receive a Word document with the text "Hello, World!" in it.
The document is then saved to a memory stream and returned as a file. The File method is used to return the document as a file with the MIME type application/vnd.openxmlformats-officedocument.wordprocessingml.document (which basically is the server saying "Hey! This is a Word document!").
Conclusion
Generating a Word document in an ASP.NET controller is quite simple to do using the Open XML library. We can create a new Word document, add content to it, and return it as a file using the File method.
To learn more about how to add content to a Word document using the Open XML library, it's worth reading the Open XML SDK documentation.
I hope this post helps you to generate Word documents in your ASP.NET applications!
Discussion in the ATmosphere