Word处理控件Aspose.Words功能演示:使用C#处理Word文档中的目录

Word文档中的目录(TOC)概述了文档中包含的内容。此外,它还允许导航到文档的特定部分。在本文中,将学习如何使用C#以编程方式在Word文档中使用目录。特别是,本文介绍如何在Word文档中添加,提取,更新或删除目录。

为了处理Word文档中的目录,将使用Aspose.Words for .NET API。旨在执行.NET应用程序中的基本和高级Word自动化功能。此外,它可以熟练掌握Word文档中目录的操作。点击下方按钮下载最新版。

下载最新版Aspose.Words(qun:761297826)icon-default.png?t=M85Bhttps://www.evget.com/product/564/download


使用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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值