In this tutorial, we will learn how to create Word document using C#, write some text with different font formatting, insert a hyperlink into it, and save the document to DOCX file format.
The following steps explain how does C# create Word document file.
Steps to Create Word Document Using C#
- Install Aspose.Words for .NET package from NuGet
- Add reference Aspose.Words and Aspose.Words.Saving namespaces
- Create instance of Document and DocumentBuilder classes
- Write some text and insert hyperlink into document
- Save the document to DOCX file format
Previously, we looked into How to Insert Header and Footer in DOCX using C#. The following code example in C# generate Word document in well-known DOCX file format. You can use the same approach to create Word document in different file formats e.g. DOC, RTF, etc. using Document.Save method. This code example can be used where .NET is installed.
Code to Generate Word Document Using C#
using System.Drawing; | |
using Aspose.Words; | |
using Aspose.Words.Saving; | |
namespace KBCodeExamples | |
{ | |
class how_to_create_word_document_using_c_sharp | |
{ | |
public static void Main(string[] args) | |
{ | |
//Set Aspose license before creating blank Word document | |
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License(); | |
AsposeWordsLicense.SetLicense(@"Aspose.Words.lic"); | |
// Create a blank Word document | |
Document doc = new Document(); | |
// Initialize a new instance of DocumentBuilder class | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// Insert a string surrounded by a border | |
builder.Font.Border.Color = Color.Green; | |
builder.Font.Border.LineWidth = 2.5d; | |
builder.Font.Border.LineStyle = LineStyle.DashDotStroker; | |
builder.Write("Text surrounded by green border."); | |
// Remove all font formatting specified explicitly | |
builder.Font.ClearFormatting(); | |
builder.InsertBreak(BreakType.ParagraphBreak); | |
builder.Write("For more information, please visit the "); | |
// Insert a hyperlink and emphasize it with custom formatting | |
// The hyperlink will be a clickable piece of text which will take us to the location specified in the URL | |
builder.Font.Color = Color.Blue; | |
builder.Font.Underline = Underline.Single; | |
builder.InsertHyperlink("Aspose Knowledge Base", "https://kb.aspose.com/", false); | |
builder.Font.ClearFormatting(); | |
builder.Writeln("."); | |
OoxmlSaveOptions saveOptions = new OoxmlSaveOptions | |
{ | |
Compliance = OoxmlCompliance.Iso29500_2008_Strict, | |
SaveFormat = SaveFormat.Docx | |
}; | |
// Save the document with strict compliance level | |
doc.Save("create word document using C#.docx", saveOptions); | |
} | |
} | |
} |
The above code example in c# create Word document from scratch. Document class represents a blank Word document. You need to associate DocumentBuilder with Document. You can use DocumentBuilder to insert different types of content into Word document e.g. table, images, text etc.