翻譯|使用教程|編輯:胡濤|2022-04-29 13:33:06.707|閱讀 298 次
概述:本文主要介紹在word文檔中插入和刪除TOC,歡迎查閱!
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
我們已經演示了如何在創建 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產品
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn