文檔金喜正規買球>>Aspose.Words使用教程>>Aspose.Words功能演示:使用C#處理Word文檔中的目錄
Aspose.Words功能演示:使用C#處理Word文檔中的目錄
Word文檔中的目錄(TOC)概述了文檔中包含的內容。此外,它還允許導航到文檔的特定部分。在本文中,將學習如何使用C#以編程方式在Word文檔中使用目錄。特別是,本文介紹如何在Word文檔中添加,提取,更新或刪除目錄。
為了處理Word文檔中的目錄,將使用Aspose.Words for .NET API。旨在執行.NET應用程序中的基本和高級Word自動化功能。此外,它可以熟練掌握Word文檔中目錄的操作。點擊下方按鈕下載最新版。
使用C#在Word文檔中添加目錄
以下是使用Aspose.Words for .NET將目錄添加到Word文檔的步驟。
- 創建Document類的實例(在加載現有Word文檔的情況下,在構造函數中提供文件的路徑)。
- 創建DocumentBuilder類的實例,并使用之前創建的Document對象對其進行初始化。
- 使用DocumentBuilder.InsertTableOfContents(“ \\ o \” 1-3 \“ \\ h \\ z \\ u”)方法插入目錄。
- 使用Document.UpdateFields()方法更新字段。
- 使用Document.Save(String)方法保存Word文檔。
下面的代碼示例演示如何在C#中的Word文檔中添加目錄。
// The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithDocument(); // Initialize document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table of contents at the beginning of the document. builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u"); // The newly inserted table of contents will be initially empty. // It needs to be populated by updating the fields in the document. doc.UpdateFields(); dataDir = dataDir + "DocumentBuilderInsertTOC_out.doc"; doc.Save(dataDir);
使用C#從Word文檔中提取目錄
以下是從Word文檔中的目錄提取字段的步驟。
- 使用Document類加載Word文檔。
- 使用Document.Range.Fields集合循環遍歷文檔中的每個Field。
- 使用Field.Type屬性檢查字段類型是否為超鏈接。
- 檢查該字段是否在內容部分的表格下面。
- 檢索字段信息并打印。
下面的代碼示例演示如何使用C#從Word文檔中提取目錄。
// The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithDocument(); string fileName = "TOC.doc"; Aspose.Words.Document doc = new Aspose.Words.Document(dataDir + fileName); foreach (Field field in doc.Range.Fields) { if (field.Type.Equals(Aspose.Words.Fields.FieldType.FieldHyperlink)) { FieldHyperlink hyperlink = (FieldHyperlink)field; if (hyperlink.SubAddress != null && hyperlink.SubAddress.StartsWith("_Toc")) { Paragraph tocItem = (Paragraph)field.Start.GetAncestor(NodeType.Paragraph); Console.WriteLine(tocItem.ToString(SaveFormat.Text).Trim()); Console.WriteLine("------------------"); if (tocItem != null) { Bookmark bm = doc.Range.Bookmarks[hyperlink.SubAddress]; // Get the location this TOC Item is pointing to Paragraph pointer = (Paragraph)bm.BookmarkStart.GetAncestor(NodeType.Paragraph); Console.WriteLine(pointer.ToString(SaveFormat.Text)); } } // End If }// End If }// End Foreach
使用C#更新Word文檔中的目錄
每當將某些內容附加到Word文檔時,都需要更新目錄。為了以編程方式執行此操作,您只需要在保存文檔之前調用Document.UpdateFields()方法即可。
使用C#刪除Word文檔中的目錄
Aspose.Words for .NET還允許您從Word文檔中刪除目錄。以下是執行此操作的步驟。
- 首先,使用Document類加載Word文檔。
- 獲取并在數組中存儲每個TOC的FieldStart節點。
- 循環遍歷節點,直到獲得FieldEnd類型(TOC的結尾)的節點。
- 使用Node.Remove()方法刪除節點并保存更新的文檔。
下面的代碼示例演示如何從C#中的Word文檔中刪除目錄。
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithStyles(); // Open a document which contains a TOC. Document doc = new Document(dataDir + "Document.TableOfContents.doc"); // Remove the first table of contents from the document. RemoveTableOfContents(doc, 0); dataDir = dataDir + "Document.TableOfContentsRemoveToc_out.doc"; // Save the output. doc.Save(dataDir); Console.WriteLine("\nSpecified TOC from a document removed successfully.\nFile saved at " + dataDir); } ////// Removes the specified table of contents field from the document. //////The document to remove the field from.///The zero-based index of the TOC to remove.public static void RemoveTableOfContents(Document doc, int index) { // Store the FieldStart nodes of TOC fields in the document for quick access. ArrayList fieldStarts = new ArrayList(); // This is a list to store the nodes found inside the specified TOC. They will be removed // At the end of this method. ArrayList nodeList = new ArrayList(); foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true)) { if (start.FieldType == FieldType.FieldTOC) { // Add all FieldStarts which are of type FieldTOC. fieldStarts.Add(start); } } // Ensure the TOC specified by the passed index exists. if (index > fieldStarts.Count - 1) throw new ArgumentOutOfRangeException("TOC index is out of range"); bool isRemoving = true; // Get the FieldStart of the specified TOC. Node currentNode = (Node)fieldStarts[index]; while (isRemoving) { // It is safer to store these nodes and delete them all at once later. nodeList.Add(currentNode); currentNode = currentNode.NextPreOrder(doc); // Once we encounter a FieldEnd node of type FieldTOC then we know we are at the end // Of the current TOC and we can stop here. if (currentNode.NodeType == NodeType.FieldEnd) { FieldEnd fieldEnd = (FieldEnd)currentNode; if (fieldEnd.FieldType == FieldType.FieldTOC) isRemoving = false; } } // Remove all nodes found in the specified TOC. foreach (Node node in nodeList) { node.Remove(); } }
如果您有任何疑問或需求,請隨時加入Aspose技術交流群(761297826),我們很高興為您提供查詢和咨詢。