Generate Word Document Using C#

Introduction

In this post, we will learn how to use DocX library to create a Word document from Visual Studio using C# language.

As we will see in this article, DocX is an open source library which is able to create a Word document from scratch by using a lot of methods and properties that help us to insert paragraphs, formatting text, style (color, size), images, tables etc… I hope it will be helpful for you.

C#

Prerequisites

Make sure you have installed Visual Studio 2017 (.Net Framework 4.6.1).

In this post, we are going to:

  • Install DocX library.
  • Create Hello World using Docx library.
  • Formatting text.
  • Add image.
  • Add table.
  • Add Hyperlink.

So let’s discover DocX library.

Install DocX library

In solution explorer, right click on References >> Manage NuGet Packages.

Now, in search input, type Docx, then select the first line as shown below, and click Install.

C#

Create Console application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select Console App (.NET Framework), name your project, and click OK.

C#

Create Hello World using Docx library

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7. using Xceed.Words.NET;  
  8.   
  9. namespace DemoDocxApp  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             string fileName = @"D:\DocxExample\exempleWord.docx";  
  16.   
  17.             var doc = DocX.Create(fileName);  
  18.   
  19.             doc.InsertParagraph("Hello Word");  
  20.   
  21.             doc.Save();  
  22.   
  23.             Process.Start("WINWORD.EXE", fileName);  
  24.   
  25.         }  
  26.     }  
  27. }  

Let’s describe step by step the code snippet above.

We are declaring fileName variable which contains the location path of our word document, then we called Create() method that accepts fileName as parameter.

After creating the Word document, we proceeded to insert “Hello World” by using InsertParagraph() method. Finally, we saved the document with the new text.

To run the program, press on F5 and we will see the output as shown below.

Output

C#

Formatting Text

  1. //Location Path  
  2. string fileName = @ "D:\DocxExample\exempleWord.docx";  
  3. //Title  
  4. string title = "Vero eos et accusamus";  
  5. //Text  
  6. string textParagraph = "" + "Dear Friends, " + Environment.NewLine + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. " + Environment.NewLine + "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. " + "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. " + "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";  

As you can see in the code snippet above. We have added variables for text and title.

Now, let’s formatting title and text by adding the following code snippet.

Formatting Title code snippet

  1. //Formatting Title  
  2. Formatting titleFormat = new Formatting();  
  3. //Specify font family  
  4. titleFormat.FontFamily = new Font("Batang");  
  5. //Specify font size  
  6. titleFormat.Size = 18 D;  
  7. titleFormat.Position = 40;  
  8. titleFormat.FontColor = System.Drawing.Color.Orange;  
  9. titleFormat.UnderlineColor = System.Drawing.Color.Gray;  
  10. titleFormat.Italic = true;  

Formatting Text code snippet

  1. //Formatting Text Paragraph  
  2. Formatting textParagraphFormat = new Formatting();  
  3. //font family  
  4. textParagraphFormat.FontFamily = new Font("Century Gothic");  
  5. //font size  
  6. textParagraphFormat.Size = 10 D;  
  7. //Spaces between characters  
  8. textParagraphFormat.Spacing = 2;  

Here, we have created an object of Formatting class which give us access to use some properties such as,

  • Font Family: is used to specify Font Family style, such as (Calibri, Comic Sans Ms, Consolas etc…)
  • Size: is responsible to set the size of text.
  • Position: means the space between paragraphs.
  • Font Color: Color of text, note that we use Drawing namespace to specify color.
  • Underline Color: is used to specify color of underline text.
  • Italics: Generally, we have two types of styles, either Italic or Bold,which accept Boolean value (True or False).

After specifying all the necessary properties, now it’s time to insert title and text by using InsertParagraph() method.

  1. //Create docx  
  2. var doc = DocX.Create(fileName);  
  3. //Insert title  
  4. Paragraph paragraphTitle = doc.InsertParagraph(title, false, titleFormat);  
  5. paragraphTitle.Alignment = Alignment.center;  
  6. //Insert text  
  7. doc.InsertParagraph(textParagraph, false, textParagraphFormat);  
  8. doc.Save();  
  9. Process.Start("WINWORD.EXE", fileName);  

Here to center title, we used Alignment property.

Now, all it’s ready, just run the program and we will see the result as shown below.

Output

C#

Add Image in Word document

Now, we would like create an image and add it within our Word document.

To do that, we will use AddImage() method and we should provide as a parameter the path where the image is located. After that, we need to call CreatePicture() method which returns picture object.

Finally, we are calling AppendPicture() method in order to save our image within the Word document.

Code snippet to add image

  1. string fileName = @ "D:\DocxExample\exempleWord.docx";  
  2. var doc = DocX.Create(fileName);  
  3. //Create a picture  
  4. Image img = doc.AddImage(@ "D:\DocxExample\word_picture.PNG");  
  5. Picture p = img.CreatePicture();  
  6. //Create a new paragraph  
  7. Paragraph par = doc.InsertParagraph("Word picture ^_^");  
  8. par.AppendPicture(p);  
  9. doc.Save();  
  10. Process.Start("WINWORD.EXE", fileName);  

Output

C#

Add Table in Word document

To add table, it’s very simple. We should use AddTable() method to specify the number of rows and columns, then we will add contents in different cells as shown below.

Finally, we need to insert table in document by using InsertTable() method. 

Code snippet to add table

  1. string fileName = @ "D:\DocxExample\exempleWord.docx";  
  2. var doc = DocX.Create(fileName);  
  3. //Create Table with 2 rows and 4 columns.  
  4. Table t = doc.AddTable(2, 4);  
  5. t.Alignment = Alignment.center;  
  6. t.Design = TableDesign.ColorfulList;  
  7. //Fill cells by adding text.  
  8. t.Rows[0].Cells[0].Paragraphs.First().Append("AA");  
  9. t.Rows[0].Cells[1].Paragraphs.First().Append("BB");  
  10. t.Rows[0].Cells[2].Paragraphs.First().Append("CC");  
  11. t.Rows[0].Cells[3].Paragraphs.First().Append("DD");  
  12. t.Rows[1].Cells[0].Paragraphs.First().Append("EE");  
  13. t.Rows[1].Cells[1].Paragraphs.First().Append("FF");  
  14. t.Rows[1].Cells[2].Paragraphs.First().Append("GG");  
  15. t.Rows[1].Cells[3].Paragraphs.First().Append("HH");  
  16. doc.InsertTable(t);  
  17. doc.Save();  
  18. Process.Start("WINWORD.EXE", fileName);  

Output

C#

Add Hyperlink

To add a hyperlink, we will use the following code snippet.

  1. Hyperlink url = doc.AddHyperlink("Google Web Site"new Uri("http://www.google.com"));  

 

As you can see, AddHyperlink() method accepts string text and target url.

Code snippet Hyperlink

  1. string fileName = @"D:\DocxExample\exempleWord.docx";  
  2. var doc = DocX.Create(fileName);  
  3. //Hyperlink  
  4. Hyperlink url = doc.AddHyperlink("Google Web Site"new Uri("http://www.google.com"));  
  5. Paragraph p1 = doc.InsertParagraph();  
  6. p1.AppendLine("Please check ").Bold().AppendHyperlink(url);  
  7. doc.Save();  
  8. Process.Start("WINWORD.EXE", fileName);  

Output

C#


Recommended Free Ebook
Similar Articles