Migration from Office Automation to DocIO

4 Feb 202524 minutes to read

Mail merge

The Mail merge feature can be used to generate reports and letters in Microsoft Word. The following code examples show how to generate an employee report from an MDB data source by using Office Automation and DocIO.

Using Microsoft Office Automation

Office Automation performs the Mail merge by executing a SQL query on the Word document. The output of the Mail merge can be sent to a new Word document. Alternatively, it can be sent to a printer, a fax machine, or forwarded to an e-mail address.

using word = Microsoft.Office.Interop.Word;

-------------

//Initializes objects.
object nullobject = Missing.Value;
object filepath = "Sample.docx";
object sqlStmt = "SELECT * FROM [Employees]";
string sDBPath = "Northwind.mdb";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filepath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
//Performs Mail Merge.     
document.MailMerge.OpenDataSource(sDBPath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref sqlStmt, ref nullobject, ref nullobject, ref nullobject);
document.MailMerge.Execute(ref nullobject);
//Sends output of Mail Merge to a new document.
document.MailMerge.Destination = word.WdMailMergeDestination.wdSendToNewDocument;
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

-------------

'Initializes objects.
Dim nullobject As Object = Missing.Value
Dim filepath As Object = "Sample.docx"
Dim sqlStmt As Object = "SELECT * FROM [Employees]"
Dim sDBPath As String = "Northwind.mdb"
'Starts the Word application.
Dim wordApp As New word.Application()
'Opens the Word document.
Dim document As word.Document = wordApp.Documents.Open(filepath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
'Performs Mail Merge.     
document.MailMerge.OpenDataSource(sDBPath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, sqlStmt, nullobject, nullobject, nullobject)
document.MailMerge.Execute(nullobject)
'Sends output of Mail Merge to a new document.
document.MailMerge.Destination = word.WdMailMergeDestination.wdSendToNewDocument
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Using DocIO

DocIO performs Mail merge by using the following methods:

The following code example performs Mail merge by using the Execute method.

string dataBase = "Northwind.mdb";
//Opens existing template.
WordDocument doc = new WordDocument("Template.docx", FormatType.Docx);
//Gets Data from the Database.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataBase);
conn.Open();
//Populates the data table.
DataTable table = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from employees", conn);
adapter.Fill(table);
adapter.Dispose();
//Performs Mail Merge.
doc.MailMerge.Execute(table);
//Saves the document.
doc.Save("Sample.docx", FormatType.Docx);
//Closes the document.
doc.Close();
Dim dataBase As String = "Northwind.mdb" 
Opens the Word document.
Dim doc As WordDocument = New WordDocument("Template.docx")
Creates database connection.
Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataBase)
conn.Open()
Populates data table.
Dim table As DataTable = New DataTable()
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter("select * from employees", conn)
adapter.Fill(table)
adapter.Dispose()
Performs Mail Merge.
doc.MailMerge.Execute(table)
Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
Closes the document.
doc.Close()

You can download a complete working sample from GitHub.

NOTE

For more information on Mail merge using DocIO, you can refer to online documentation link: MailMerge

Find and Replace

This section illustrates how to perform a simple find and replace operation in a Word document by using Microsoft Office Automation and DocIO.

Using Microsoft Office Automation

The following code example illustrates how to search for a word in a Word document, replace it with another word and save the document under a new name.

using word = Microsoft.Office.Interop.Word;

---------

//Initializes objects.
object nullobject = Missing.Value;
object filepath = "Template.docx";
object newFilePath = "Sample.docx";
object item = word.WdGoToItem.wdGoToPage;
object whichItem = word.WdGoToDirection.wdGoToFirst;
object replaceAll = word.WdReplace.wdReplaceAll;
object forward = true;
object matchAllWord = true;
object matchCase = false;
object originalText = "Hello";
object replaceText = "World";
object save = true;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filepath, ref nullobject, ref nullobject, ref nullobject, ref nullobject,ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
//Searches and replaces text.
document.GoTo(ref item, ref whichItem, ref nullobject, ref nullobject);
foreach (word.Range rng in document.StoryRanges)
{
    rng.Find.Execute(ref originalText, ref matchCase, ref matchAllWord, ref nullobject, ref nullobject,ref nullobject, ref forward, ref nullobject, ref nullobject, ref replaceText, ref replaceAll, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
}
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

----------------

Initializes objects.
Dim nullobject As Object = Missing.Value
Dim filePath As Object = "Template.docx"
Dim newFilePath As Object = "Sample.docx"
Dim item As Object = word.WdGoToItem.wdGoToPage
Dim whichItem As Object = word.WdGoToDirection.wdGoToFirst
Dim replaceAll As Object = word.WdReplace.wdReplaceAll
Dim forward As Object = True
Dim matchAllWord As Object = True
Dim matchCase As Object = False
Dim originalText As Object = "Hello"
Dim replaceText As Object = "World"
Dim save As Object = True
Dim falseObj As Object = False
Starts the Word application.
Dim wordApp As word.Application = New word.Application()
Opens the Word document.
Dim doc As word.Document = wordApp.Documents.Open(filePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, falseobj, nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
Searches and replaces text.
doc.GoTo(item, whichItem, nullobject, nullobject)
For Each rng As word.Range In doc.StoryRanges
    rng.Find.Execute(originalText, matchCase, matchAllWord, nullobject, nullobject, nullobject, forward, nullobject, nullobject, replaceText, replaceAll, nullobject, nullobject, nullobject, nullobject)
Next
Saves the document.
doc.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
Closes the document.
doc.Close(nullobject, nullobject, nullobject)
Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Using DocIO

The following code example illustrates how to perform a simple find and replace operation by using DocIO.

//Opens the Word document.
WordDocument document = new WordDocument("Template.docx",FormatType.Docx);
//Defines replacement text.
string replaceText = "World";
//Performs replace.
document.Replace(new Regex("Hello"), replaceText);
//Saves the document.
document.Save("Sample.docx", FormatType.Docx);
//Closes the document.
document.Close();
Opens the Word document.
Dim document As WordDocument = New WordDocument("Template.docx")
Defines text to be replaced.
Dim replaceText As String = "World"
Performs replace.
document.Replace(New Regex("Hello"), replaceText)
Saves the document.
document.Save("Sample.docx", FormatType.Docx)
Closes the document.
document.Close()

You can download a complete working sample from GitHub.

NOTE

For more information on performing the find and replace operation using DocIO, you can refer to online documentation link: Find and Replace

Bookmarks

Bookmarks identify the location of text in a Word document that you can name and identify for future reference.

Using Microsoft Office Automation

The following code example illustrates how to insert a bookmark for a range of text by using Office Automation.

using word = Microsoft.Office.Interop.Word;

---------

//Initializes objects.
object nullobject = Missing.Value;
object newFilePath = "Sample.docx";
//Starts a Word application.
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
//Creates a new Word document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref nullobject);
Microsoft.Office.Interop.Word.Document document = wordApp.ActiveDocument;
//Adds a paragraph to the document.
Microsoft.Office.Interop.Word.Paragraph oPara1;
oPara1 = document.Content.Paragraphs.Add(ref nullobject);
oPara1.Range.Text = "Bookmark with one word selected";
//Defines start and end positions of bookmark range.
object start = oPara1.Range.Text.IndexOf("word");
object end = oPara1.Range.Text.LastIndexOf(" ");
object rng = document.Range(ref start, ref end);
//Adds bookmark.
document.Bookmarks.Add("one_word", ref rng);
//Saves document and quits application.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
//Closes document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

----------------

Initializes objects.
Dim nullobject As Object = Missing.Value
Dim newFilePath As Object = "Sample.docx"
Starts a Word application.
Dim wordApp As word.Application = New word.Application()
Creates a new Word document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim doc As word.Document = wordApp.ActiveDocument
Adds a paragraph to the document.
Dim oPara As word.Paragraph
oPara = doc.Content.Paragraphs.Add(nullobject)
oPara.Range.Text = "Bookmark with one word selected"
Defines the start and end positions of bookmark range.
Dim startobj As Object = oPara.Range.Text.IndexOf("word")
Dim endobj As Object = oPara.Range.Text.LastIndexOf(" ")
Dim rng As Object = doc.Range(startobj, endobj)
Adds bookmark.
doc.Bookmarks.Add("one_word", rng)
Saves document.
doc.SaveAs(newFilePath)
Closes document.
doc.Close(nullobject, nullobject, nullobject)
Quits application.
wordApp.Quit()

Using DocIO

The following code example illustrates how to insert the bookmark by using DocIO. Here, the AppendBookmarkStart() and AppendBookmarkEnd() methods are used to add the bookmark.

//Creates a new Word document.
WordDocument doc = new WordDocument();
//Adds new section
IWSection section = doc.AddSection();
//Adds new paragraph
IWParagraph paragraph = section.AddParagraph();
paragraph.AppendText("Simple Bookmark");
paragraph = section.AddParagraph();
paragraph.AppendText("Bookmark with one ");
//Inserts bookmark.
paragraph.AppendBookmarkStart("one_word");
paragraph.AppendText("word");
paragraph.AppendBookmarkEnd("one_word");
paragraph.AppendText(" selected");
//Saves the document.
doc.Save("Sample.docx", FormatType.Docx);
//Closes the document.
doc.Close();
Creates a new Word document.
Dim doc As WordDocument = New WordDocument()
Adds new section
Dim section As IWSection = doc.AddSection()
Adds new paragraph
Dim paragraph As IWParagraph = section.AddParagraph()
paragraph.AppendText("Simple Bookmark")
paragraph = section.AddParagraph()
paragraph.AppendText("Bookmark with one ")
Inserts bookmark.
paragraph.AppendBookmarkStart("one_word")
paragraph.AppendText("word")
paragraph.AppendBookmarkEnd("one_word")
paragraph.AppendText(" selected")
Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
Closes the document.
doc.Close()

You can download a complete working sample from GitHub.

Page Numbers

Page numbers can be added to the Word document in headers or footers.

Using Microsoft Office Automation

The following code example illustrates how page numbers can be inserted to the footer of the Word document by adding a page number field.

using word = Microsoft.Office.Interop.Word;

---------

//Initializes objects.
object filepath = "Sample.docx";
object nullobject = Missing.Value;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filepath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
document.Activate();
//Seeks the page footer.
wordApp.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
//Formats the footer.
wordApp.Selection.Paragraphs.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
wordApp.ActiveWindow.Selection.Font.Name = "Arial";
wordApp.ActiveWindow.Selection.Font.Size = 8;
//Adds page numbers in the footer.
Object CurrentPage = word.WdFieldType.wdFieldPage;
wordApp.ActiveWindow.Selection.Fields.Add(wordApp.Selection.Range, ref CurrentPage, ref nullobject, ref nullobject);
//Saves the document.
document.Save();
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

----------------

Initializes objects.
Dim nullobject As Object = Missing.Value
Dim filePath As Object =  "Sample.docx"
Dim falseobj As Object = False
Starts the application.
Dim wordApp As word.Application = New word.Application()
Adds a new Word document.
Dim document As word.Document = wordApp.Documents.Open(filePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, falseobj, nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
document.Activate()
Seeks the page footer.
wordApp.ActiveWindow.ActivePane.View.SeekView = word.WdSeekView.wdSeekCurrentPageFooter
Formats the footer.
wordApp.Selection.Paragraphs.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter
wordApp.ActiveWindow.Selection.Font.Name = "Arial"
wordApp.ActiveWindow.Selection.Font.Size = 8
Adds page numbers in the footer.
Dim CurrentPage As Object = word.WdFieldType.wdFieldPage
wordApp.ActiveWindow.Selection.Fields.Add(wordApp.Selection.Range, CurrentPage, nullobject, nullobject)
Saves the document.
document.Save()
Closes the document.
document.Close(nullobject, nullobject, nullobject)
Quits application.
wordApp.Quit()

Using DocIO

The following code example illustrates how page numbers are inserted to the footer of the Word document by using DocIO.

//Opens the Word document.
WordDocument doc = new WordDocument("Template.docx", FormatType.Docx);
//Iterates through sections
foreach (WSection sec in doc.Sections)
{
    IWParagraph para = sec.AddParagraph();
    //Appends page field to the paragraph
    para.AppendField("footer", FieldType.FieldPage);
    para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
    sec.PageSetup.PageNumberStyle = PageNumberStyle.Arabic;
    //Adds paragraph to footer
    sec.HeadersFooters.Footer.Paragraphs.Add(para);
}
//Saves the document.
doc.Save("Sample.docx",FormatType.Docx);
//Closes the document.
doc.Close();
Opens the Word document.
Dim doc As WordDocument = New WordDocument("Template.docx", FormatType.Docx)
Iterates through sections
For Each sec As WSection In doc.Sections
    Dim para As IWParagraph = sec.AddParagraph()
    Appends page field to the paragraph
    para.AppendField("footer", FieldType.FieldPage)
    para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center
    sec.PageSetup.PageNumberStyle = PageNumberStyle.Arabic
    Adds paragraph to footer
    sec.HeadersFooters.Footer.Paragraphs.Add(para)
Next
Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
Closes the document.
doc.Close()

You can download a complete working sample from GitHub.

Document Watermarks

Watermarks are text or pictures that appear behind document text.

Using Microsoft Office Automation

The following code example illustrates how to insert a text watermark as a shape by using Office Automation.

using word = Microsoft.Office.Interop.Word;

---------

//Initializes objects.
object nullobject = Missing.Value;
object newFilePath = "Sample.docx";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Creates a new Word document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref nullobject);
word.Document document = wordApp.ActiveDocument;
//Seeks the current page header.
wordApp.ActiveWindow.ActivePane.View.SeekView = word.WdSeekView.wdSeekCurrentPageHeader;
//Inserts watermark.
word.Shape watermark = wordApp.Selection.HeaderFooter.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "Watermark", "Arial", (float)48, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, 0, 0, ref nullobject);
//Sets watermark properties.
watermark.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
watermark.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
watermark.Fill.Solid();
watermark.Fill.ForeColor.RGB = (Int32)word.WdColor.wdColorGray30;
//Sets focus back to the document.
wordApp.ActiveWindow.ActivePane.View.SeekView = word.WdSeekView.wdSeekMainDocument;
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

----------------

Initializes objects.
Dim nullobject As Object = Missing.Value
Dim newFilePath As Object = "Sample.docx"
Starts the application.
Dim wordApp As word.Application = New word.Application()
Creates a new Word document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim doc As word.Document = wordApp.ActiveDocument
Seeks the current page header.
wordApp.ActiveWindow.ActivePane.View.SeekView = word.WdSeekView.wdSeekCurrentPageHeader
Adds text watermark to the document.
Dim watermark As word.Shape = wordApp.Selection.HeaderFooter.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,"Watermark", "Arial", 48, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, 0, 0, nullobject)
Sets watermark properties.
watermark.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue
watermark.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse
watermark.Fill.Solid()
watermark.Fill.ForeColor.RGB = CType(word.WdColor.wdColorGray30, Integer)
Saves the document.
doc.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
Closes the document.
doc.Close(nullobject, nullobject, nullobject)
Quits application.
wordApp.Quit()

Using DocIO

DocIO enables you to add a text watermark and a picture watermark to a Word document. The following code example shows how to insert the picture watermark to the Word document.

//Creates a new Word document.
WordDocument doc = new WordDocument();
doc.EnsureMinimal();
//Adds picture watermark to the document.
PictureWatermark picWatermark = new PictureWatermark();
picWatermark.Scaling = 120f;
picWatermark.Washout = true;
doc.Watermark = picWatermark;
picWatermark.Picture = Image.FromFile(ImagesPath + "Water lilies.jpg");
//Saves the document.
doc.Save("Sample.docx", FormatType.Docx);
//Closes the document.
doc.Close();
Creates a new Word document.
Dim doc As WordDocument = New WordDocument()
doc.EnsureMinimal()
Adds picture watermark to the document.
Dim picWatermark As PictureWatermark = New PictureWatermark()
picWatermark.Scaling = 120f
picWatermark.Washout = True
doc.Watermark = picWatermark
picWatermark.Picture = Image.FromFile(ImagesPath and "Water lilies.jpg")
Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
Closes the document.
doc.Close()

You can download a complete working sample from GitHub.

NOTE

For more information on adding watermarks to a Word document using DocIO, refer to the online documentation link: Applying Watermark

Headers and Footers

The headers and footers can be inserted with text, graphics, and any other information that is contained in the document.

Using Microsoft Office Automation

The following code example illustrates how to add headers and footers to a Word document. In this example, page numbers are inserted to the header and a text is inserted to the footer.

using word = Microsoft.Office.Interop.Word;

---------

//Initializes objects.
object nullobject = Missing.Value;
object filePath = "Template.docx";
object newFilePath = "Sample.docx";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
//Adds header and footer to each section in the document.
foreach (word.Section section in document.Sections)
{
    object fieldEmpty = word.WdFieldType.wdFieldPage;
    object autoText = "AUTOTEXT  \"Page X of Y\" ";
    object preserveFormatting = true;
    //Footer.
    section.Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = "Internal";
    section.Footers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphLeft;
    //Header.
    section.Headers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Fields.Add(section.Headers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range,reffieldEmpty, ref autoText, ref preserveFormatting);
    section.Headers[word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphRight;
}
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

----------------

'Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim filePath As Object = "Template.docx"
Dim newFilePath As Object = "Sample.docx"
'Starts the application.
Dim wordApp As word.Application = New word.Application()
'Opens the document.
Dim document As word.Document = wordApp.Documents.Open(filePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
'Adds header and footer to each section in the document.
For Each section As word.Section In document.Sections
    Dim fieldEmpty As Object = word.WdFieldType.wdFieldPage
    'Footer.
    section.Footers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Text = "Internal"
    section.Footers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphLeft
    'Header.
    section.Headers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Fields.Add(section.Headers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range, fieldEmpty, nullobject, nullobject)
    section.Headers(word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphRight
Next
'Saves the document.
document.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit()

Using DocIO

You can set the header and footer by using the HeadersFooters property in the Word document section. To access a particular header/footer, you can use the following properties of WHeadersFooters class:

//Opens a Word document.
WordDocument doc = new WordDocument("Template.docx");
//Adds header and footer to each section in the document.
foreach (WSection sec in doc.Sections)
{
    //Header.
    WParagraph para = new WParagraph(doc);
    para.AppendField("page", FieldType.FieldPage);
    para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Right;
    sec.HeadersFooters.Header.Paragraphs.Add(para);
    /Footer.
    WParagraph para1 = new WParagraph(doc);
    para1.AppendText("Internal");
    para1.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left;
    sec.HeadersFooters.Footer.Paragraphs.Add(para1);
}
//Saves the document.
doc.Save("Sample.docx", FormatType.Docx);
//Closes the document.
doc.Close();
Opens the Word document.
Dim doc As WordDocument = New WordDocument("Template.docx")
Adds header and footer to each section in the document.
For Each sec As WSection In doc.Sections
    Header.
    Dim para As WParagraph = New WParagraph(doc)
    para.AppendField("page", FieldType.FieldPage)
    para.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Right
    sec.HeadersFooters.Header.Paragraphs.Add(para)
    Footer.
    Dim para1 As WParagraph = New WParagraph(doc)
    para1.AppendText("Internal")
    para1.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left
    sec.HeadersFooters.Footer.Paragraphs.Add(para1)
Next
Saves the document.
doc.Save("Sample.docx", FormatType.Docx)
Closes the document.
doc.Close()

You can download a complete working sample from GitHub.

Character Formatting

Character formatting defines the appearance of the text in a Word document. This section illustrates how to apply character level formatting to the Word document.

Using Microsoft Office Automation

The following code example illustrates how to apply the character formatting to the Word document by using the Range properties.

using word = Microsoft.Office.Interop.Word

----------------

//Initializes objects.
object nullobject = System.Reflection.Missing.Value;
object newFilePath = "Sample.docx";
object falseObj = false;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Creates a new Word document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref nullobject);
word.Document doc = wordApp.ActiveDocument;
//Defines the range for formatting.
object start = 0;
object end = 0;
word.Range rng = doc.Range(ref start, ref end);
rng.Text = "New Text";
rng.Font.Name = "Arial";
rng.Font.Size = 14;
//Saves the document.
doc.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
//Closes the document.
doc.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

----------------

Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim newFilePath As Object = "Sample.docx"
Dim falseObj As Object = False
Starts the Word application.
Dim wordApp As word.Application = New word.Application()
Creates a new Word document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim doc As word.Document = wordApp.ActiveDocument
Defines the range for formatting.
Dim start As Object = 0
Dim endobj As Object = 0
Dim rng As word.Range = doc.Range(start, endobj)
rng.Text = "New Text"
rng.Font.Name = "Arial"
rng.Font.Size = 14
Saves the document.
doc.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
Closes the document.
doc.Close(nullobject, nullobject, nullobject)
Quits the application.
wordApp.Quit()

Tables

Tables are used to organize information and to display the information in rows and columns. You can also add images or even other tables to the table.

Using Microsoft Office Automation

The following code example illustrates how to insert a table to a Word document, where the table contains three rows and two columns.

using word = Microsoft.Office.Interop.Word;

---------

//Initializes the objects.
object nullobject = System.Reflection.Missing.Value;
object newFilePath = "Sample.docx";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Creates a new document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref nullobject);
word.Document document = wordApp.ActiveDocument;
//Inserts the table.
object start = 0;
object end = 0;
word.Range tableLocation = document.Range(ref start, ref end);
document.Tables.Add(tableLocation, 3, 2, ref nullobject, ref nullobject);
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject,ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

---------

'Initializes the objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim newFilePath As Object = "Sample.docx"
'Starts the Word application.
Dim wordApp As New word.Application()
'Creates a new document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim document As word.Document = wordApp.ActiveDocument
'Inserts the table.
Dim start As Object = 0
Dim [end] As Object = 0
Dim tableLocation As word.Range = document.Range(start, [end])
document.Tables.Add(tableLocation, 3, 2, nullobject, nullobject)
'Saves the document.
document.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Using DocIO

The following code example shows how to insert an empty table to a Word document. The ResetCells() method is used to specify the number of rows and columns in a table.

//Creates a new Word document.
WordDocument document = new WordDocument();
IWSection section = document.AddSection();
//Adds a table to the document.
IWTable table = section.AddTable();
table.ResetCells(3, 2);
//Saves the document.
document.Save("Sample.docx",FormatType.Docx);
//Closes the document.
document.Close();
'Creates a new Word document.
Dim document As New WordDocument()
Dim section As IWSection = document.AddSection()
'Adds a table to the document.
Dim table As IWTable = section.AddTable()
table.ResetCells(3, 2)
'Saves the document.
document.Save("Sample.docx",FormatType.Docx);
'Closes the document.
document.Close()

You can download a complete working sample from GitHub.

NOTE

For more information on creating tables using DocIO, refer to online documentation link: Working with Tables

Comments

Comments are used to include additional information to a paragraph or text in a Word document. Comments can be added or modified whenever needed and deleted when the comment has served its purpose.

Using Microsoft Office Automation

The following code example illustrates how to add comments to a Word document. You need to define the range of text where the comment is to be added.

using word = Microsoft.Office.Interop.Word;

---------

//Initializes objects.
object nullobject = System.Reflection.Missing.Value;
object newFilePath = "Sample.docx";
//Starts the Word application.
word.Application wordApp = new word.Application();
//Creates a new document.
wordApp.Documents.Add(ref nullobject, ref nullobject, ref nullobject, ref nullobject);
word.Document doc = wordApp.ActiveDocument;
//Inserts text to the Word document.
object start = 0;
object end = 0;
word.Range rng = doc.Range(ref start, ref end);
rng.Text = "New Text";
//Adds comment to the inserted text.
object text = "Comment goes here";
doc.Comments.Add(rng, ref text);
//Saves the document.
doc.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
//Closes the document.
doc.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
Imports word = Microsoft.Office.Interop.Word

---------

Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim newFilePath As Object = "Sample.docx"
Starts the Word application.
Dim wordApp As word.Application = New word.Application()
Creates a new document.
wordApp.Documents.Add(nullobject, nullobject, nullobject, nullobject)
Dim doc As word.Document = wordApp.ActiveDocument
Inserts text to the Word document.
Dim startobj As Object = 0
Dim endobj As Object = 0
Dim rng As word.Range = doc.Range(startobj, endobj)
rng.Text = "New Text"
Adds comment to the inserted text.
Dim text As Object = "Comment goes here"
doc.Comments.Add(rng, text)
Saves the document and quits application.
doc.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
Closes the document.
doc.Close(nullobject, nullobject, nullobject)
Quits the application.
wordApp.Quit()

Using DocIO

You can insert comments to a paragraph or text in a Word document by using DocIO. The following code example shows how to insert comments to a Word document.

//Creates a new Word document.
WordDocument doc = new WordDocument();
IWSection section = doc.AddSection();
//Adds a paragraph to the document.
IWParagraph para = section.AddParagraph();
para.AppendText("New Text");
//Adds comment to the paragraph.
para.AppendComment("Comment goes here");
//Saves the document.
doc.Save("Sample.doc", FormatType.Doc);
Creates a new Word document.
Dim doc As WordDocument = New WordDocument()
Dim section As IWSection = doc.AddSection()
Adds a paragraph to the document.
Dim para As IWParagraph = section.AddParagraph()
para.AppendText("New Text")
para.AppendComment("Comment goes here")
Saves the document.
doc.Save("Sample.doc", FormatType.Doc)

You can download a complete working sample from GitHub.

NOTE

For more information on working with the comments using DocIO, you can refer to the online documentation link: Working with Comments

Document Protection

You can protect your Word documents with or without a password from anyone accidentally or deliberately modifying the Word documents. You can specify the protection type for preserving the Word documents.

Using Microsoft Office Automation

WdProtectionType is used to specify the protection type of the Word document.

//Initializes objects.
object nullobject = System.Reflection.Missing.Value;
object filepath = "Template.docx";
object newFilePath = "Sample.docx";
object noReset = false;
object password = System.String.Empty;
object useIRM = false;
object enforceStyleLock = false;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document to be protected.
word.Document document = wordApp.Documents.Open(ref filepath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
//Sets "Allow only Comments" protection to Word document.
document.Protect(word.WdProtectionType.wdAllowOnlyComments, ref noReset, ref password, ref useIRM, ref enforceStyleLock);
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
'Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim filepath As Object = "Template.docx"
Dim newFilePath As Object = "Sample.docx"
Dim noReset As Object = False
Dim password As Object = System.[String].Empty
Dim useIRM As Object = False
Dim enforceStyleLock As Object = False
'Starts the Word application.
Dim wordApp As New Word.Application()
'Opens the Word document that is to be protected.
Dim document As Word.Document = wordApp.Documents.Open(filepath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
'Sets "Allow only Comments" protection to Word document.
document.Protect(Word.WdProtectionType.wdAllowOnlyComments, noReset, password, useIRM, enforceStyleLock)
'Saves the document.
document.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Using DocIO

DocIO uses ProtectionType property to specify the protection type of the Word document. This property uses the following values:

//Loads the existing Word document by using DocIO instance
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
//Sets "Allow only Comments" protection to Word document.
document.ProtectionType = Syncfusion.DocIO.ProtectionType.AllowOnlyComments;
//Saves and closes the document.
document.Save("Sample.docx", FormatType.Docx);
document.Close();
'Loads the existing Word document by using DocIO instance
Dim document As New WordDocument("Template.docx", FormatType.Docx)
'Sets "Allow only Comments" protection to Word document.
document.ProtectionType = Syncfusion.DocIO.ProtectionType.AllowOnlyComments
'Saves and closes the document.
document.Save("Sample.docx", FormatType.Docx)
document.Close()

You can download a complete working sample from GitHub.

Refer to the online documentation link for more details about the ways to protect the Word documents by using DocIO:
Protecting word document from editing

Table of Contents

Table of contents can be generated by applying the heading styles to text in a Word document. To create the table of contents in Microsoft Word, click Table of Contents from the Table of Contents group on the References tab.

Using Microsoft Office Automation

The following code example shows how to insert and update table of contents in a Word document.

//Initializes objects.
object nullobject = System.Reflection.Missing.Value;
object filepath = "Template.docx";
object newFilePath = "Sample.docx";
object trueobj = true;
//Starts the Word application.
word.Application wordApp = new word.Application();
//Opens the Word document.
word.Document document = wordApp.Documents.Open(ref filepath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
wordApp.Visible = false;
//Defines the range for TOC in the document.
object tocstart = 0;
object tocend = 0;
word.Range rngToc = document.Range(ref tocstart, ref tocend);
//Adds TOC.
word.TableOfContents tableOfContents = document.TablesOfContents.Add(rngToc, ref trueobj, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref trueobj, ref trueobj, ref trueobj, ref trueobj, ref trueobj, ref trueobj);
//Updates TOC.
tableOfContents.Update();
//Saves the document.
document.SaveAs(ref newFilePath, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
//Closes the document.
document.Close(ref nullobject, ref nullobject, ref nullobject);
//Quits the application.
wordApp.Quit(ref nullobject, ref nullobject, ref nullobject);
'Initializes objects.
Dim nullobject As Object = System.Reflection.Missing.Value
Dim filepath As Object = "Template.docx"
Dim newFilePath As Object = "Sample.docx"
Dim trueobj As Object = True
'Starts the Word application.
Dim wordApp As New Word.Application()
'Opens the Word document.
Dim document As Word.Document = wordApp.Documents.Open(filepath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
wordApp.Visible = False
'Defines the range for TOC in the document.
Dim tocstart As Object = 0
Dim tocend As Object = 0
Dim rngToc As Word.Range = document.Range(tocstart, tocend)
'Adds TOC.
Dim tableOfContents As Word.TableOfContents = document.TablesOfContents.Add(rngToc, trueobj, nullobject, nullobject, nullobject, nullobject, trueobj, trueobj, trueobj, trueobj, trueobj, trueobj)
'Updates TOC.
tableOfContents.Update()
'Saves the document.
document.SaveAs(newFilePath, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject, nullobject)
'Closes the document.
document.Close(nullobject, nullobject, nullobject)
'Quits the application.
wordApp.Quit(nullobject, nullobject, nullobject)

Using DocIO

The following code example illustrates how to insert and update the table of contents in a Word document by using DocIO.

//Loads the existing Word document by using DocIO instance
WordDocument document = new WordDocument("Template.docx", FormatType.Docx);
IWSection section = document.Sections[0];
//Appends TOC to the first paragraph of the document.
WParagraph paragraph = new WParagraph(document);
TableOfContent tableOfContents = paragraph.AppendTOC(1, 3);
section.Paragraphs.Insert(0, paragraph);
//Updates table of contents.
document.UpdateTableOfContents();
//Saves and closes the document.
document.Save("Sample.docx", FormatType.Docx);
document.Close();
'Loads the existing Word document by using DocIO instance
Dim document As New WordDocument("Template.docx", FormatType.Docx)
Dim section As IWSection = document.Sections(0)
'Appends TOC to the first paragraph of the document.
Dim paragraph As New WParagraph(document)
Dim tableOfContents As TableOfContent = paragraph.AppendTOC(1, 3)
section.Paragraphs.Insert(0, paragraph)
'Updates table of contents.
document.UpdateTableOfContents()
'Saves and closes the document.
document.Save("Sample.docx", FormatType.Docx)
document.Close()

You can download a complete working sample from GitHub.

Refer to the online documentation link for more information about adding the table of contents to the Word document by using DocIO:
Working with table of contents.