Insert a Table of Contents in Word using C#

Insert a table of contents in Word using C# by following this brief article. It helps to establish the environment by sharing the necessary resources, a list of steps for writing the application, and a sample code demonstrating how to add contents page in Word using C#. You will learn to add a TOC to an existing Word file by parsing its contents.

Steps to Create a Table of Contents in Word using C#

  1. Set the environment to use Aspose.Words for .NET to insert TOC
  2. Load the Word file into the Document object and initialize the DocumentBuilder object
  3. Add the title of TOC with the desired style
  4. Insert table of contents and insert a page break
  5. Populate the empty table of contents
  6. Save the output Word file having TOC in it

You can insert contents page in Word using C# with the help of these steps. Initiate the process by loading the Word file and configure the DocumentBuilder class object that supports adding a table of contents. Add the title and table of contents using the InsertTableOfContents() method and populate the empty table of contents by calling the UpdateFields() method.

Code to Generate a Table of Contents in Word using C#

using System;
using Aspose.Words;
class Program
{
static void Main(string[] args) // Insert table of contents in Word using C#
{
new License().SetLicense("License.lic");
// Load the document
Document doc = new Document("example03.docx");
// Instantiate the DocumentBuilder object
DocumentBuilder builder = new DocumentBuilder(doc);
// Create ParagraphFormat object
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
// Store the existing style name
string defaultStyle = paragraphFormat.StyleName;
// Set style name and text alignment for the table of contents
paragraphFormat.StyleName = "Title";
paragraphFormat.Alignment = ParagraphAlignment.Center;
// Add title of TOC
builder.Writeln("Table of contents");
// Restore the text style
paragraphFormat.StyleName = defaultStyle;
// Insert a table of contents
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Insert page break for TOC
builder.InsertBreak(BreakType.PageBreak);
// Populate the empty table of contents
doc.UpdateFields();
// Save document with TOC
doc.Save("output.docx");
Console.WriteLine("Done");
}
}

Use this code to make a contents page in Word using C#. The InsertTableOfContents() requires switches to control the behavior of the table of contents, say 1-3 used for addressing Heading 1, 2, and 3, ‘\h’ for using hyperlinks, and ‘\u’ for setting outline levels. The default TOC is empty and filled using the UpdateFields() method.

This article has taught us how to add a table of contents in Word using C#. To insert headers and footers, refer to the article on how to insert header and footer in DOCX using C#.

 English