C++读写word文档(.docx)DuckX库的使用详解

2025-09-25 12:50

本文主要是介绍C++读写word文档(.docx)DuckX库的使用详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《C++读写word文档(.docx)DuckX库的使用详解》DuckX是C++库,用于创建/编辑.docx文件,支持读取文档、添加段落/片段、编辑表格,解决中文乱码需更改编码方案,进阶功能含文本替换...

DuckX是一个用于创建和编辑 Microsoft Word (.docx) 文件的 C++ 库。

一、基本用法

1. 读取文档

#include <IOStream>
#include "duckx.hpp"

int main() {
	duckx::Document doc("foo.docx");
	doc.open();

	for (auto p = doc.paragraphs(); p.has_next(); p.next()) {
		for (auto r = p.runs(); r.has_phpnext(); r.next()) {
			std::cout << r.get_text() << std::endl;
		}
	}

	return 0;
}

运行结果如下:

C++读写word文档(.docx)DuckX库的使用详解

中文乱码的原因时由于将UTF-8字符串使用GBK编码显示了,更改编码方案即可。

3. 添加段落

#include "duckx.hpp"
#include python<iostream>

int main() {
    // 加载文档
    duckx::Document doc("foo.docx");
    doc.open();

    // 遍历段落
    duckx::Paragraph& paragraph = doc.paragraphs();
    while China编程(paragraph.has_next()) {
        // 如果需要在某段之后插入段落
        if (paragraph.runs().get_text() == "AAA") {
python            paragraph.insert_paragraph_after("This is a new paragraph.");
        }

        // 移动到下一个段落
        paragraph.next();
    }

    // 保存修改后的文档
    doc.save();

    return 0;
}

原始文件如下:

C++读写word文档(.docx)DuckX库的使用详解

修改文件如下:

C++读写word文档(.docx)DuckX库的使用详解

4. 添加片段

#include "duckx.hpp"
#include <iostream>

int main() {
    // 加载文档
    duckx::Document doc("foo.docx");
    doc.open();

    // 遍历段落
    duckx::Paragraph& paragraph = doc.paragraphs();
    while (paragraph.has_next()) {
        // 在某段中追加运行文本
        if (paragraph.runs().get_text() == "AAA") {
            paragraph.add_run(" Added new text here.");
        }

        // 移动到下一个段落
        paragraph.next();
    }

    // 保存修改后的文档
    doc.save();

    return 0;
}

C++读写word文档(.docx)DuckX库的使用详解

3. 编辑表格

#include "duckx.hpp"
#include <iostream>

int main() {
    // 加载文档
    duckx::Document doc("table.docx");
    doc.open();

    // 遍历表格
    duckx::Table& table = doc.tables();
    while (table.has_next()) {
        duckx::TableRow& row = table.rows();
        while (row.has_next()) {
            duckx::TableCell& cell = row.cells();
            while (cell.has_next()) {
                // 在单元格内新增段落
                duckx::Paragraph& paragraph = cell.paragraphs();
                if (paragraph.runs().get_text() == "") {
                    paragraph.add_run("2024");
                }
                cell.next();
            }
            row.next();
        }
        table.next();
    }

    // 保存修改后的文档
    doc.save();

    return 0;
}

原始文档如下:

C++读写word文档(.docx)DuckX库的使用详解

修改文档如下:

C++读写word文档(.docx)DuckX库的使用详解

二、进阶用法

1. 文本替换

#include "duckx.hpp"
#include <iostream>
#include <unordered_map>
#include <string>

void Replace(const std::string & path, const std::unordered_map<std::string, std::string>& replacements) {
    // 打开文档
    duckx::Document doc(path);
    doc.open();

    // 遍历段落
    for (auto p = doc.paragraphs(); p.has_next(); p.next()) {
        // 遍历运行文本
        for (auto r = p.runs(); r.has_next(); r.next()) {
            // 获取当前运行文本内容
            std::string text = r.get_text();

            // 检查键值对中的键是否存在于当前文本中
            for (const auto& [key, value] : replacements) {
                // 如果找到匹配键,进行替换
                size_t pos = text.find(key);
                if (pos != std::string::npos) {
                    text.replace(pos, key.length(), value);
                    r.set_text(text);
                }
            }
        }
    }

    // 保存修改后的文档
    doc.save();
}

int main() {
    std::unordered_map<std::string, std::string> replacements = {
        {"{name}", "John Doe"},
        {"{date}", "2024-11-29"},
        {"{city}", "New York"}
    };
    Replace("foo.docx", replacements);
    std::cout << "Replacements complete. Saved to foo.docx." << std::endl;
    return 0;
}

C++读写word文档(.docx)DuckX库的使用详解

C++读写word文档(.docx)DuckX库的使用详解

进阶版:可同时替换普通文本和表格中的文本

#include "duckx.hpp"
#include <iostream>
#include <unordered_map>
#include <string>

void Replace(const std::string& path, const std::unordered_map<std::string, std::string>& replacements) {
    // 打开文档
    duckx::Document doc(path);
    doc.open();

    // 遍历段落
    for (auto p = doc.paragraphs(); p.has_next(); p.next()) {
        // 遍历运行文本
        for (auto r = p.runs(); r.has_next(); r.next()) {
            // 获取当前运行文本内容
            std::string text = r.get_text();

            // 检查键值对中的键是否存在于当前文本中
            for (const auto& [key, value] : replacements) {
                // 如果找到匹配键,进行替换
                size_t pos = text.find(key);
                if (pos != std::string::npos) {
                    text.replace(pos, key.length(), value);
         android           r.set_text(text);
                }
            }
        }
    }

    // 遍历表格
    for (auto t = doc.tables(); t.has_next(); t.next()) {
        // 遍历表格行
        for (auto r = t.rows(); r.has_next(); r.next()) {
            // 遍历表格单元格
            for (auto c = r.cells(); c.has_next(); c.next()) {
                // 遍历单元格中的段落
                for (auto p = c.paragraphs(); p.has_next(); p.next()) {
                    // 遍历单元格段落中的运行文本
                    for (auto r = p.runs(); r.has_next(); r.next()) {
                        // 获取当前运行文本内容
                        std::string text = r.get_text();

                        // 检查键值对中的键是否存在于当前文本中
                        for (const auto& [key, value] : replacements) {
                            // 如果找到匹配键,进行替换
                            size_t pos = text.find(key);
                            if (pos != std::string::npos) {
                                text.replace(pos, key.length(), value);
                                r.set_text(text);
                            }
                        }
                    }
                }
            }
        }
    }

    // 保存修改后的文档
    doc.save();
}

int main() {
    std::unordered_map<std::string, std::string> replacements = {
        {"{name}", "John Doe"},
        {"{date}", "2024-11-29"},
        {"{city}", "New York"}
    };
    Replace("foo.docx", replacements);
    std::cout << "Replacements complete. Saved to foo.docx." << std::endl;
    return 0;
}

2. 合并文档

只能合并文本

#include "duckx.hpp"
#include <iostream>

int main() {
    // 加载第一个文档
    duckx::Document doc1("document1.docx");
    doc1.open();

    // 加载第二个文档
    duckx::Document doc2("document2.docx");
    doc2.open();

    // 将第二个文档的段落添加到第一个文档
    duckx::Paragraph &paragraph2 = doc2.paragraphs();
    while (paragraph2.has_next()) {
        // 获取第二个文档中的段落
        std::string text = paragraph2.runs().get_text();

        // 在第一个文档中插入段落
        doc1.paragraphs().insert_paragraph_after(text);

        paragraph2.next();
    }

    // 将第二个文档的表格添加到第一个文档
    duckx::Table &table2 = doc2.tables();
    while (table2.has_next()) {
        duckx::TableRow &row2 = table2.rows();
        while (row2.has_next()) {
            duckx::TableCell &cell2 = row2.cells();
            while (cell2.has_next()) {
                // 获取第二个文档中的单元格
                std::string cellText = cell2.paragraphs().runs().get_text();

                // 在第一个文档中插入单元格
                doc1.tables().rows().cells().add_run(cellText);

                cell2.next();
            }
            row2.next();
        }
        table2.next();
    }

    // 保存合并后的文档
    doc1.save();

    std::cout << "Documents merged and saved to document1.docx." << std::endl;
    return 0;
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持China编程(www.chinasem.cn)。

这篇关于C++读写word文档(.docx)DuckX库的使用详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1156022

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

MyBatis常用XML语法详解

《MyBatis常用XML语法详解》文章介绍了MyBatis常用XML语法,包括结果映射、查询语句、插入语句、更新语句、删除语句、动态SQL标签以及ehcache.xml文件的使用,感兴趣的朋友跟随小... 目录1、定义结果映射2、查询语句3、插入语句4、更新语句5、删除语句6、动态 SQL 标签7、ehc

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三