Word处理控件Aspose.Words功能演示:在 C# 中的 Word 文档中添加、编辑和删除目录

Aspose.Words 是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。此外,API支持所有流行的Word处理文件格式,并允许将Word文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。

Aspose API支持流行文件格式处理,并允许将各类文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。

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

一、下载在 Word 文档中添加、编辑或删除 TOC 的 C# API

为了使用 Word 文档中的目录,我们将使用Aspose.Words for .NET。所述 API 旨在从 .NET 应用程序中执行基本和高级 Word 自动化功能。此外,它使您可以很好地控制 Word 文档中目录的操作。您可以下载API 或使用NuGet安装它。

PM> Install-Package Aspose.Words

二、在 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 文档中添加目录。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// 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.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 文档中删除目录。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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);
}
/// <summary>
/// Removes the specified table of contents field from the document.
/// </summary>
/// <param name="doc">The document to remove the field from.</param>
/// <param name="index">The zero-based index of the TOC to remove.</param>
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();
}
}

以上便是在 C# 中的 Word 文档中添加、编辑和删除目录详细步骤 ,要是您还有其他关于产品方面的问题,欢迎咨询我们,或者加入我们官方技术交流群。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值