{
"$type": "site.standard.document",
"canonicalUrl": "https://johnnyreilly.com/posts/generate-word-doc-in-asp-net",
"description": "Learn how to generate a Word document using the Open XML library in ASP.NET.",
"path": "/posts/generate-word-doc-in-asp-net",
"publishedAt": "2024-03-19T00:00:00.000Z",
"site": "at://did:plc:yy3apqjlms24kso7ahn7lbmb/site.standard.publication/3mova7c4nho2b",
"tags": [
"asp.net"
],
"textContent": "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.\n\n\n\nOpen XML\n\nTo 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:\n\nGenerating a Word document in an ASP.NET controller\n\nWith 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:\n\nIn 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.\n\nThe 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!\").\n\nConclusion\n\nGenerating 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.\n\nTo 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.\n\nI hope this post helps you to generate Word documents in your ASP.NET applications!",
"title": "Generate a Word document in ASP.NET"
}