Some People use Microsoft Office Interop library to create Word documents, however they often ask the question how to create Word document in C# without interop. This is where Aspose.Words for .NET comes into play to help create Word document in C# easily.
This question is being answered in the below steps along with the C# code sample. This shows how easily and efficiently you can create DOCX or DOC file from scratch in your .NET applications, be it a .NET console utility, Windows application, or ASP.NET web project. Aspose.Words seamlessly work with every .NET platform technology.
Steps to Create Word Document in C# without Automation
- Use Aspose.Words for .NET NuGet package
- Add reference to Aspose.Words namespace
- Use SetLicense method to apply Aspose license
- Create a new Document Class instance
- Create a DocumentBuilder Class object and pass Document object in the constructor
- Set required properties of the DocumentBuilder object
- Save the output Word document as a file or a stream
Code to Create Word Document in C# without Automation
using System; | |
//Add reference to Aspose.Words for .NET API | |
//Use following namespaces to Word Document generator code | |
using Aspose.Words; | |
namespace CreateWordDocumentWithoutInterop | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//Set Aspose license before creating Word document without Interop | |
//using Aspose.Words for .NET | |
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License(); | |
AsposeWordsLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
//Create an instance of Document class of Aspose.Words for .NET | |
//This initiates a blank Word document | |
Document WordDocumentWithoutInterop = new Document(); | |
//An instance of DocumentBuilder class is used to add | |
//content to the Word Document | |
DocumentBuilder WordDocumentBuilder = new DocumentBuilder(WordDocumentWithoutInterop); | |
//Add some text with bold formatting | |
WordDocumentBuilder.Bold = true; | |
WordDocumentBuilder.Writeln("We're adding this line of text in the word document using DocumentBuilder Class"); | |
WordDocumentBuilder.Writeln("This does not require Office Interop or Office Automation"); | |
//Finally, save the generated word document to docx format | |
WordDocumentWithoutInterop.Save("Word_Document_Created_Without_Interop_using_CSharp.docx"); | |
} | |
} | |
} |
In this C# code example, we created a simple Word document with just two lines of text and applied bold attribute to the text. However, you can do a lot more and expand above code by adding tables, cells, and different other objects of the Word Document Object Model (DOM).
To execute above C# code of Aspose.Words for .NET API, you’re not required to install Microsoft Word on your computer or the server where application will be installed. This makes creating word document a lot easier and quicker.