Aspose API支持流行文件格式处理,并允许将各类文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。
Aspose.words是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。此外,API支持所有流行的Word处理文件格式,并允许将Word文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。
目录 (TOC) 是 Word 文档的重要组成部分。它提供文档内容的概述,并允许您快速导航到所需的部分。您可能会发现自己需要以编程方式从 Word 文档中添加、提取、更新或删除目录。为此,本文将教您如何使用 C++ 处理 Word 文件中的目录。
一、下载用于处理 Word 文档中的目录的 C++ API
Aspose.Words for C++是一个原生 C++ 库,允许您创建、阅读、修改和转换 Microsoft Word 文档。此外,它还支持处理 Word 文件中的目录。您可以通过NuGet安装 API,也可以直接从“下载”部分下载。
PM> Install-Package Aspose.Words.Cpp
二、在 Word 文档中添加目录
以下是在 Word 文档中添加目录的步骤。
- 使用Document类加载 Word 文件。
 - 使用之前创建的Document对象创建DocumentBuilder类的实例。
 - 使用DocumentBuilder->InsertTableOfContents(System::String 开关)方法插入目录。
 - 使用Document->UpdateFields()方法填充目录。
 - 使用Document->Save(System::String fileName)方法保存 Word 文档。
 
以下示例代码展示了如何使用 C++ 在 Word 文档中添加目录。
// Source and output directory paths. System::String sourceDataDir = u"SourceDirectory\\"; System::String outputDataDir = u"OutputDirectory\\"; // Load the Word file System::SharedPtr<Document> doc = System::MakeObject<Document>(sourceDataDir + u"Sample 5.docx"); // Create an instance of the DocumentBuilder class System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc); // Insert a table of contents at the beginning of the document. builder->InsertTableOfContents(u"\\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(); // Output file path System::String outputPath = outputDataDir + u"AddTOC.docx"; // Save the Word file doc->Save(outputPath);

三、从 Word 文档中提取目录
以下是从 Word 文档中提取目录的步骤。
- 使用Document类加载 Word 文件。
 - 使用Document->get_Range()->get_Fields()方法检索字段并遍历它们。
 - 检查字段是否为FieldType::FieldHyperlink类型。
 - 检查该字段是否属于目录。
 - 检索并打印字段信息。
 
以下示例代码演示了如何使用 C++ 从 Word 文档中提取目录。
 
 // Source direvctory
System::String inputDataDir = u"SourceDirectory\\";
// Load the Word file
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"SampleTOC.docx");
// Loop through the fields
for (System::SharedPtr<Field> field : System::IterateOver(doc->get_Range()->get_Fields()))
{
// Get FieldHyperlink fields
if (field->get_Type() == FieldType::FieldHyperlink)
{
System::SharedPtr<FieldHyperlink> hyperlink = System::DynamicCast<FieldHyperlink>(field);
// Check if field belongs to TOC
if (hyperlink->get_SubAddress() != nullptr && hyperlink->get_SubAddress().StartsWith(u"_Toc"))
{
System::SharedPtr<Paragraph> tocItem = System::DynamicCast<Paragraph>(field->get_FieldStart()->GetAncestor(NodeType::Paragraph));
std::cout << System::StaticCast<Node>(tocItem)->ToString(SaveFormat::Text).Trim().ToUtf8String() << std::endl;
std::cout << "------------------" << std::endl;
if (tocItem != nullptr)
{
System::SharedPtr<Bookmark> bm = doc->get_Range()->get_Bookmarks()->idx_get(hyperlink->get_SubAddress());
// Get the location this TOC Item is pointing to
System::SharedPtr<Paragraph> pointer = System::DynamicCast<Paragraph>(bm->get_BookmarkStart()->GetAncestor(NodeType::Paragraph));
std::cout << System::StaticCast<Node>(pointer)->ToString(SaveFormat::Text).ToUtf8String() << std::endl;
}
}
}
} 
 
四、更新 Word 文档中的目录
如果文档的内容已经更新,并且您需要在目录中反映这些更改,您只需加载 Word 文件并调用Document->UpdateFields()方法。该方法会根据修改后的内容更新目录。在此之后,保存更新的 Word 文档。
五、从 Word 文档中删除目录
以下是从 Word 文档中删除目录的步骤。
- 使用Document类加载 Word 文件。
 - 检索并存储FieldStart节点的列表。
 - 循环遍历节点,直到到达指定目录结尾的NodeType::FieldEnd类型的节点。
 - 使用Node->Remove()方法删除目录。
 - 使用Document->Save(System::String fileName)方法保存 Word 文档。
 
以下示例代码显示如何使用 C++ 从 Word 文档中删除目录。
 
 void RemoveTableOfContents(const System::SharedPtr<Document>& doc, int32_t index)
{
// Store the FieldStart nodes of TOC fields in the document for quick access.
std::vector<System::SharedPtr<FieldStart>> fieldStarts;
// This is a list to store the nodes found inside the specified TOC. They will be removed
// at the end of this method.
std::vector<System::SharedPtr<Node>> nodeList;
for (System::SharedPtr<FieldStart> start : System::IterateOver<System::SharedPtr<FieldStart>>(doc->GetChildNodes(NodeType::FieldStart, true)))
{
if (start->get_FieldType() == FieldType::FieldTOC)
{
// Add all FieldStarts which are of type FieldTOC.
fieldStarts.push_back(start);
}
}
// Ensure that the TOC specified by the passed index exists.
if (index > fieldStarts.size() - 1)
{
throw System::ArgumentOutOfRangeException(u"TOC index is out of range");
}
bool isRemoving = true;
// Get the FieldStart of the specified TOC.
System::SharedPtr<Node> currentNode = fieldStarts[index];
while (isRemoving)
{
// It is safer to store these nodes and delete them all at once later.
nodeList.push_back(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->get_NodeType() == NodeType::FieldEnd)
{
System::SharedPtr<FieldEnd> fieldEnd = System::DynamicCast<FieldEnd>(currentNode);
if (fieldEnd->get_FieldType() == FieldType::FieldTOC)
{
isRemoving = false;
}
}
}
// Remove all nodes found in the specified TOC.
for (System::SharedPtr<Node> node : nodeList)
{
node->Remove();
}
}
int main()
{
// Source and output directory paths.
System::String sourceDataDir = u"SourceDirectory\\";
System::String outputDataDir = u"OutputDirectory\\";
// Open a Word document
System::SharedPtr<Document> doc = System::MakeObject<Document>(sourceDataDir + u"SampleTOC.docx");
// Remove the first table of contents from the document.
RemoveTableOfContents(doc, 0);
// Output file path
System::String outputPath = outputDataDir + u"RemoveTOC.docx";
// Save the Word file
doc->Save(outputPath);
} 
 
以上便是使用 C++ 在 Word 文档中添加或删除页眉和页脚详细步骤 ,要是您还有其他关于产品方面的问题,欢迎咨询我们,或者加入我们官方技术交流群。



















