我们已经演示了如何在创建 word 文档时添加一个全新的 TOC 。本文将向您展示如何将 TOC 插入到现有的带有样式的 Word 文档中,并从 Word 文档中删除 TOC。
首先,查看带有 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)