如何使用C ++以编程方式在Word文档中使用目录?

2023-11-03

目录(TOC)是Word文档的重要组成部分。它提供了文档内容的概述,并允许您快速导航到所需的部分。您可能会遇到需要以编程方式从Word文档中添加,提取,更新或删除目录的情况。为此,本文将教您如何使用C ++处理Word文件中的目录。

让我们探索以下有关的内容:

  • 在Word文档中添加目录
  • 从Word文档中提取目录
  • 更新Word文档中的目录
  • 从Word文档中删除目录

Aspose.Words for C ++ 是本机C ++库,允许您创建,读取,修改和转换Microsoft Word文档。此外,它还支持使用Word文件中的目录。

>>你可以这里下载Aspose.Words for C ++ 最新版测试体验。


在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::SharedPtrdoc = System::MakeObject(sourceDataDir + u"Sample 5.docx");

// Create an instance of the DocumentBuilder class
System::SharedPtrbuilder = System::MakeObject(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开发工具Aspose.Words功能演示:使用C ++在Word文档中使用目录

从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::SharedPtrdoc = System::MakeObject(inputDataDir + u"SampleTOC.docx");

// Loop through the fields
for (System::SharedPtrfield : System::IterateOver(doc->get_Range()->get_Fields()))
{
	// Get FieldHyperlink fields
	if (field->get_Type() == FieldType::FieldHyperlink)
	{
		System::SharedPtrhyperlink = System::DynamicCast(field);

		// Check if field belongs to TOC
		if (hyperlink->get_SubAddress() != nullptr && hyperlink->get_SubAddress().StartsWith(u"_Toc"))
		{
			System::SharedPtrtocItem = System::DynamicCast(field->get_FieldStart()->GetAncestor(NodeType::Paragraph));
			std::cout << System::StaticCast(tocItem)->ToString(SaveFormat::Text).Trim().ToUtf8String() << std::endl; std::cout << "------------------" << std::endl; if (tocItem != nullptr) { System::SharedPtrbm = doc->get_Range()->get_Bookmarks()->idx_get(hyperlink->get_SubAddress());

				// Get the location this TOC Item is pointing to
				System::SharedPtrpointer = System::DynamicCast(bm->get_BookmarkStart()->GetAncestor(NodeType::Paragraph));
				std::cout << System::StaticCast(pointer)->ToString(SaveFormat::Text).ToUtf8String() << std::endl; } } } }

更新Word文档中的目录

如果文档的内容已更新,并且您需要在目录中反映这些更改,则只需加载Word文件并调用 Document-> UpdateFields() 方法。此方法将根据修改后的内容更新目录。之后,保存更新的Word文档。

以下是从Word文档中删除目录的步骤。

  • 使用Document 类加载Word文件 。
  • 检索并存储FieldStart节点的列表。
  • 遍历节点,直到到达指定目录结尾的类型NodeType :: FieldEnd的节点。
  • 使用Node-> Remove()方法删除目录。
  • 使用Document-> Save(System :: String fileName)方法保存Word文档。

下面的示例代码显示了如何使用C ++从Word文档中删除目录。

void RemoveTableOfContents(const System::SharedPtr& doc, int32_t index)
{
	// Store the FieldStart nodes of TOC fields in the document for quick access.
	std::vectorfieldStarts;
	// This is a list to store the nodes found inside the specified TOC. They will be removed
	// at the end of this method.
	std::vectornodeList;

	for (System::SharedPtrstart : System::IterateOver(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::SharedPtrcurrentNode = 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::SharedPtrfieldEnd = System::DynamicCast(currentNode);
			if (fieldEnd->get_FieldType() == FieldType::FieldTOC)
			{
				isRemoving = false;
			}
		}
	}

	// Remove all nodes found in the specified TOC.
	for (System::SharedPtrnode : 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::SharedPtrdoc = System::MakeObject(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);
}

如果您有任何疑问或需求,请随时加入Aspose技术交流群(761297826),我们很高兴为您提供查询和咨询。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用C ++以编程方式在Word文档中使用目录? 的相关文章

随机推荐

  • python设置excel表头_python xlsxwriter:添加表时将标头保留在Excel中

    I have a panda dataframe that I write to a xslx file and would like to add a table over that data I would also like to k
  • 【LeetCode刷题】136、只出现一次的数字 - java

    题目 给定一个非空整数数组 除了某个元素只出现一次以外 其余每个元素均出现两次 找出那个只出现了一次的元素 说明 你的算法应该具有线性时间复杂度 你可以不使用额外空间来实现吗 示例 方法 方法一 排序遍历法 先将其进行排序 因为重复的只可能
  • Linux命令操作:用sort和awk命令,进行复杂条件过滤

    原文 https www toutiao com i6968352645211963941 多 浩如烟海 参数之杂 多如繁星 需求引导 用到再学 以使用为目的 适当延伸 是一个最实际最有效的办法 某天 我突然想生成一个文件 记录 dev下的
  • 输入三个坐标,判断三角形,并输出面积和周长。

    include
  • MySQL的索引

    什么是索引 索引是一种特殊的文件 InnoDB数据表上的索引是表空间的一个组成部分 它们包含着对数据表里所有记录的引用指针 索引是一种数据结构 数据库索引 是数据库管理系统中一个排序的数据结构 以协助快速查询 更新数据库表中数据 索引的实现
  • shiro入门详解以及使用方法、shiro认证与shiro授权

    shiro介绍 什么是shiro shiro是Apache的一个开源框架 它将软件系统的安全认证相关的功能抽取出来 实现用户身份认证 权限授权 加密 会话管理等功能 组成了一个通用的安全认证框架 它可以实现如下的功能 1 验证用户 2 对用
  • 字符串的输入输出处理

    1391 字符串的输入输出处理 Time Limit 1 Sec Memory Limit 64 MBSubmit 333 Solved 71 Submit Status BBS Description 字符串的输入输出处理 Input 第
  • 线程安全的单例模式:饿汉模式&懒汉模式

    目录 一 单例模式 二 饿汉模式 1 特点 2 实现关键 3 代码实现 三 懒汉模式 1 特点 2 实现关键 3 代码实现 一 单例模式 单例模式 一种典型的设计模式 应用场景 一个类只能实例化一个对象 向外提供统一访问接口的场景 作用 对
  • C++基本使用--菱形继承(多继承)

    菱形继承 多继承 多继承 菱形继承 虚继承virtual 多继承 include
  • 犀牛高程点建地形gh插件电池组_Grasshopper快速生成地形

    简述 根据CAD高程点及高程信息在Grasshopper中快速生成地形模型 所需文件 CAD地形文件 所需软件 Rhino Grasshopper 插件 Human Weaverbird Meshtools Meshedit 可自行前往Fo
  • 计算机网络学习笔记:第四章

    计算机网络学习笔记 第四章 学习书籍 计算机网络 自顶向下方法 第四章 网络层 数据平面 其他章节请参阅 计算机网络 自顶向下方法 第一章 计算机网络和因特网 计算机网络 自顶向下方法 第二章 应用层 计算机网络 自顶向下方法 第三章 运输
  • 区块链技术加密算法为什么不可篡改

    区块链采用密码学的方法来保证已有数据不可能被篡改 这个是误解最多的部分 因为很多人一提到区块链就只觉得是这个 诚然 这部分很重要 而且确实区块链也因此得名 但这只是区块链的定义的一部分 这个部分的两个核心要点是 1 密码学哈希函数 2 非对
  • SpringBoot关键面试题

    什么是springboot 用来简化spring应用的初始搭建以及开发过程 使用特定的方式来进行配置 properties或yml文件 创建独立的spring引用程序 main方法运行 嵌入的Tomcat 无需部署war文件 简化maven
  • 如何使用 scp 将文件夹从远程复制到本地?

    问 如何使用 scp 将文件夹从远程复制到本地主机 我使用 ssh 登录到我的服务器 然后 我想将远程文件夹 foo 复制到本地 home user Desktop 我如何实现这一目标 答1 huntsbot com 高效赚钱 自由工作 s
  • Qt中关于emit和moc_*.cpp的自动生成

    关于Qt中的emit 函数 直接查看emit的定义 define emit 可以发现emit仅仅是个宏定义符号 编译器宏替换后就是个 空白 根本就不会编译它 所以代码里完全可以去掉这个符号 反之也可以在任何代码前加上这个符号 如这行代码em
  • C语言详解——枚举类型

    在程序中 可能需要为某些整数定义一个别名 我们可以利用预处理指令 define来完成这项工作 您的代码可能是 define MON 1 define TUE 2 define WED 3 define THU 4 define FRI 5
  • 说一下反三角函数atan等的角度计算值,弧度制和角度制

    我们平时在进行数学计算是 往往会用到三角函数和反三角函数 最常用的反三角函数大概就是atan了 因为这个相当于给定两点之间直线的夹角了 1 正切函数图像 这时正切函数图像 高中的我们就应该知道 正切函数是周期函数 即同一个值 有很多角度值对
  • html 中shadow DOM 的使用

    什么是shadow DOM An important aspect of web components is encapsulation being able to keep the markup structure style and b
  • antV/g2的使用

    antV g2 特点 以数据驱动 安装 npm instal antv g2 使用 准备一个容器 div div 执行代码 1 引入 import
  • 如何使用C ++以编程方式在Word文档中使用目录?

    目录 TOC 是Word文档的重要组成部分 它提供了文档内容的概述 并允许您快速导航到所需的部分 您可能会遇到需要以编程方式从Word文档中添加 提取 更新或删除目录的情况 为此 本文将教您如何使用C 处理Word文件中的目录 让我们探索以