How to Create Table of Contents (TOC) in C#

A table of contents, usually shorten as 'Contents' and abbreviated as TOC, is one of the most common function used in the professional documents. It gives readers clear and brief information of the document. This How To Guide for developers will explain the steps of create table of contents in C# with the help of a .NET word API Spire.Doc for .NET.

Firstly, view the screenshot of the table of contents created by the Spire.Doc in C#.

How to create Table of Contents (TOC) in C#

In this example, we call the method of AppendTOC to add the table of contents directly and use ApplyStyle to set the styles. Here comes to the steps of how to create TOC in C#.

Name Space we will use:

using Spire.Doc;
using Spire.Doc.Documents;

Step 1: Create a new document and add section and paragraph to the document.

Document doc = new Document();
Section section = doc.AddSection();
Paragraph para = section.AddParagraph();

Step 2: Add the Table of Contents and add the text that you want to appear in the table of contents.

para.AppendTOC(1, 3);
//Add a new paragraph to the section
Paragraph para1 = section.AddParagraph();
//Add text to the paragraph
para1.AppendText("Head1");

Step 3: Set the style for the paragraph.

para1.ApplyStyle(BuiltinStyle.Heading1);

Step 4: Add the second paragraph and set the style.

Paragraph para2 = section.AddParagraph();
para2.AppendText("Head2");
para2.ApplyStyle(BuiltinStyle.Heading2);

Step 5: Update the table of contents and save the document to file.

doc.UpdateTableOfContents();
doc.SaveToFile("CreateTableOfContent.docx", FileFormat.Docx);

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;

namespace TableofContents
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            Section section = doc.AddSection();
            Paragraph para = section.AddParagraph();

            para.AppendTOC(1, 3);
            Paragraph para1 = section.AddParagraph();
            para1.AppendText("Head1");

            para1.ApplyStyle(BuiltinStyle.Heading1);

            Paragraph para2 = section.AddParagraph();
            para2.AppendText("Head2");
            para2.ApplyStyle(BuiltinStyle.Heading2);

            doc.UpdateTableOfContents();
            doc.SaveToFile("CreateTableOfContent.docx", FileFormat.Docx);

        }
    }
}