How to Create A Word Document in C#

mhamzap10

Mehr Muhammad Hamza

Posted on January 24, 2024

How to Create A Word Document in C#

Microsoft Word is a widely used word-processing application that allows users to create, edit, and format documents. In this article, we will explore how to create Word documents programmatically using C#, a powerful and versatile programming language. We will leverage the capabilities provided by Iron Word to interact with Word and generate documents dynamically.

In this tutorial, you will learn how to create a Word document in the C# using the IronWord library. This library lets you interact with the Word application and programmatically manipulate its documents. You will learn how to create a new document, add text, Paragraph, Style it, and insert images and tables.

How to Create a Professional Word Document Using C#:

  1. Open a project in Visual Studio
  2. Install Iron Word Library
  3. Create a Word document and Load it into Memory
  4. Add Text
  5. Add Paragraph
  6. Add Style to Text
  7. Add Image
  8. Add Table

What is the Iron Word.?

Iron Word is a C# library that allows you to create, edit, and manipulate Word documents in .NET applications. It supports various features such as formatting, tables, images, headers, footers, bookmarks, and hyperlinks. It is compatible with .NET 8, 7, 6, 5, Core, Standard, and Framework, and works on Windows, Linux, macOS, iOS, and Android.

We can use Iron Word in the following scenarios but not limited to:

  1. Document generation: You can use Iron Word to create Word documents from scratch or templates, with options to customize the content, layout, and formatting. You can also use Iron Word to convert HTML, PDF, or images to Word documents, or vice versa.
  2. Document editing: You can use Iron Word to modify existing Word documents by adding, deleting, or merging pages, changing metadata, applying passwords and permissions, adding comments and tracking changes, and more.
  3. Document manipulation: You can use Iron Word to work with various elements of Word documents, such as text, images, tables, headers, footers, bookmarks, and hyperlinks. You can also use Iron Word to manipulate Word styles, themes, and fonts.
  4. Document automation: You can use Iron Word to automate Microsoft Word tasks such as mail merge, data extraction, document comparison, and document validation.

Creating Word Document in C

Let's start step by step to creating a new Word document in C#.

Install Iron Word Nuget Package:

The first step is installing the Iron Word NuGet Package in our Project. We can install it by entering the following command in the Package Manager Console.
Install-Package IronWord
This command will Install Iron Word and all its dependencies in our project.

Create Word document:

The following code snippet will create an empty Word document.



static void Main(string[] args)
{
    WordDocument doc = new WordDocument();
    doc.SaveAs("myTestDocument.docx");
}


Enter fullscreen mode Exit fullscreen mode

WordDocument object will create a Microsoft Word document in memory, and then we can save it on our local machine using the SaveAs() method.
An empty document is created successfully as shown below.
Missing Value Object
Now, that our Word document is created, Let's add some text and Paragraphs to the existing Word document.

Add Text in Our Document:

The following simple code will add text to our document.



WordDocument doc = new WordDocument();
doc.AddText("Hello! This Document is Created Using Iron Word Library");
doc.SaveAs("myTestDocument.docx");


Enter fullscreen mode Exit fullscreen mode

We can use the AddText() method provided by WordDocument Class. This method adds text to the Word document in a simpler way. The text is added to the document created successfully as shown below.
Word Doc

Add paragraph in MS Word documents:

The following code snippet will add a Paragraph to our Word document.



static void Main(string[] args)
 {
// Create a Word Document
     WordDocument doc = new WordDocument();
     TextRun introText = new TextRun("This is an example paragraph written for C# Create Word Document Tutorial");
     Paragraph paragraph = new Paragraph();
     // Add text
     paragraph.AddTextRun(introText);
     // Add paragraph
     doc.AddParagraph(paragraph);
     // Export docx
     doc.SaveAs("myTestDocument.docx");
 }


Enter fullscreen mode Exit fullscreen mode

We have created an object of TextRun() with the text we want to include in the paragraph. Then we created a new Paragraph Object. We then call the AddTextRUn() method of the Paragraph Class and pass the introText variable as a parameter. In this way, we can easily add a paragraph to our MS Word documents.

Let's Add Styling to our Paragraph.

Add Styling to the Paragraph:

Let's add styling to our Microsoft Word document in C# with minimal and simpler code.



static void Main(string[] args)
 {
     // Create word document
     WordDocument doc = new WordDocument();

     // Configure text
     TextRun textRun = new TextRun();
     textRun.Text = "Add text using IronWord with Styling in C#";
     textRun.Style = new TextStyle()
     {
         FontFamily = "ADLaM Display",
         FontSize = 36,
         TextColor = new IronColor(Color.Violet),
         IsBold = true,
         IsItalic = true,
         IsUnderline = true,
         IsSuperscript = false,
         IsStrikethrough = false,
         IsSubscript = false
     };
     Paragraph paragraph = new Paragraph();
     // Add text
     paragraph.AddTextRun(textRun);
     // Add paragraph
     doc.AddParagraph(paragraph);
     // Export docx
     doc.SaveAs("myTestDocument.docx");
 }


Enter fullscreen mode Exit fullscreen mode

The above sample code will style our Paragraph. It sets Fonts Family to "ADLaM Display", Font Size to 72, Color to Violet, and sets Bold, italic, and underlined text. We can use this styling variable to style our paragraph as we please. This is the simplest and easiest way to style our text in C#. In this way, we can easily manipulate MS Word documents.
The output document is as:
Word App Microsoft

Add Image to MS Word document in C#:

Let's add an image to our Word document. The following code will load an existing Word document and add an image.



WordDocument document = new WordDocument(); // word document class
IronWord.Models.Image image = new IronWord.Models.Image("C-Sharp-Logo.png");
image.Width = 400; // In unit pixel
image.Height = 300; // In unit pixel
Paragraph paragraph = new Paragraph();

// Add image
paragraph.AddImage(image);

// Add paragraph 
document.AddParagraph(paragraph);
document.SaveAs("myTestDocumentWithImage.docx");


Enter fullscreen mode Exit fullscreen mode

At first, we created a new document object to create a new Word document in memory. In the next line, We have loaded the Image using IronWord.Models.Image() method, after then we can pass that image to the paragraph object using the AddImage() method.
new document Microsoft

Let's explore more advanced features by adding a Table to our document.

Add Table In Word Document using C#:

The following code will create and add a table to our MS Word document using Iron Word.



static void Main(string[] args)
 {
     // Create table cell
     TableCell cell = new TableCell();

     TextRun textRun = new TextRun();
     textRun.Text = "Sample Table for Create Word Document in C# Tutorial";
     // Add textrun to the cell
     cell.AddContent(new Paragraph(textRun));
     // Configure border style
     BorderStyle borderStyle = new BorderStyle();
     borderStyle.BorderColor = new IronColor(IronSoftware.Drawing.Color.Black);
     borderStyle.BorderValue = IronWord.Models.Enums.BorderValues.Thick;
     borderStyle.BorderSize = 5;

     // Configure table border
     TableBorders tableBorders = new TableBorders()
     {
         TopBorder = borderStyle,
         RightBorder = borderStyle,
         BottomBorder = borderStyle,
         LeftBorder = borderStyle,
     };

     cell.Borders = tableBorders;

     // Create row and add cell
     TableRow row = new TableRow();
     row.AddCell(cell);
     row.AddCell(cell);

     // Create table and add row
     Table table = new Table();
     table.AddRow(row);

     // Create new Word document from the table
     WordDocument doc = new WordDocument(table);

     // Export Word document
     doc.SaveAs("myTestDocumentWithTable.docx");
 }



Enter fullscreen mode Exit fullscreen mode

We can style our table by using table Border, and Bolder Style Object. The table cell Object is used to add content in the respective row and column. Iron Word makes working with Word documents super easy. The output is as:
Add Table to MS Word in C#

Conclusion:

In conclusion, leveraging the Iron Word library in C# provides a robust solution for dynamically creating and manipulating Word documents. This tutorial guided you through the process of installing the library and demonstrated its versatility in adding text, paragraphs, styling, images, and tables to our documents. Iron Word's compatibility with various .NET platforms and operating systems makes it a valuable tool for developers seeking efficient and customizable solutions for document automation and content generation. As you explore the library further, you'll discover its extensive capabilities, making it a go-to choice for seamlessly integrating Word document functionality into C# applications. Iron Word offers a free trial to explore its features in any environment be it development, staging, or production. You may purchase a commercial license after exploring completely using the trial version.

💖 💪 🙅 🚩
mhamzap10
Mehr Muhammad Hamza

Posted on January 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to Create A Word Document in C#
csharp How to Create A Word Document in C#

January 24, 2024