• Word控件Spire.Doc 【表单域】教程(六):C#在word文档中插入和删除TOC


     

    我们已经演示了如何在创建 word 文档时添加一个全新的 TOC 。本文将向您展示如何将 TOC 插入到现有的带有样式的 Word 文档中,并从 Word 文档中删除 TOC。

    Spire.Doc for.NET 最新下载

    首先,查看带有 Title、Heading1 和 Heading 2 样式的示例文档:

    下面的代码片段显示了如何将目录 (TOC) 插入到文档中。

    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);
    
    }
    }
    }
    

    从文档中删除目录

    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);
    
    }
    }
    }
    

    欢迎下载|体验更多E-iceblue产品 技术交流Q群(767755948)  

  • 相关阅读:
    如何在 Vue 3 中使用 Ant Design
    vue2相关
    我的互联网秋招经历
    对线程池的理解
    vue-element-switch用法
    Linux系统目录简单说明
    重修SpringMVC(二)
    命名路由、组件中name的作用
    浅析vue的createApp方法
    MYSQL 窗体汇总函数
  • 原文地址:https://blog.csdn.net/m0_67129275/article/details/126135557