C# insert and remove TOC from the word document

We have already demonstrated how to add a brand new TOC when we create the word documents. This article will show you how to insert a TOC to the existing word documents with styles and remove the TOC from the word document.

Firstly, view the sample document with Title, Heading1 and Heading 2 styles:

C# insert and remove TOC from the word document

The below code snippet shows how to insert a Table of contents (TOC) into a document.

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Text.RegularExpressions;
namespace InsertTOC
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new instance of Document and load the document from file.
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);

            //Add the TOC to the document
            TableOfContent toc = new TableOfContent(doc, "{\\o \"1-3\" \\h \\z \\u}");
            Paragraph p = doc.LastSection.Paragraphs[0];
            p.Items.Add(toc);
            p.AppendFieldMark(FieldMarkType.FieldSeparator);
            p.AppendText("TOC");
            p.AppendFieldMark(FieldMarkType.FieldEnd);
            doc.TOC = toc;

            //Update the table of contents
            doc.UpdateTableOfContents();

            //Save the document to file
            doc.SaveToFile("Result.docx", FileFormat.Docx);

        }
    }
}

C# insert and remove TOC from the word document

Removing a Table of Contents from the Document

using Spire.Doc;
using System.Text.RegularExpressions;
namespace RemoveTOC
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the document from file with TOC 
            Document doc = new Document();
            doc.LoadFromFile("Result.docx", FileFormat.Docx2010);

            //get the first body from the first section
            Body body = doc.Sections[0].Body;

            //remove TOC from first body
            Regex regex = new Regex("TOC\\w+");
            for (int i = 0; i < body.Paragraphs.Count; i++)
            {
                if (regex.IsMatch(body.Paragraphs[i].StyleName))
                {
                    body.Paragraphs.RemoveAt(i);
                    i--;
                }
            }
            //save the document to file
            doc.SaveToFile("RemoveTOC.docx", FileFormat.Docx2010);

        }
    }
}

C# insert and remove TOC from the word document