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中的Schema校验技术与实践示例详解

《Java中的Schema校验技术与实践示例详解》本主题详细介绍了在Java环境下进行XMLSchema和JSONSchema校验的方法,包括使用JAXP、JAXB以及专门的JSON校验库等技术,本文... 目录1. XML和jsON的Schema校验概念1.1 XML和JSON校验的必要性1.2 Sche

使用MapStruct实现Java对象映射的示例代码

《使用MapStruct实现Java对象映射的示例代码》本文主要介绍了使用MapStruct实现Java对象映射的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、什么是 MapStruct?二、实战演练:三步集成 MapStruct第一步:添加 Mave

Java抽象类Abstract Class示例代码详解

《Java抽象类AbstractClass示例代码详解》Java中的抽象类(AbstractClass)是面向对象编程中的重要概念,它通过abstract关键字声明,用于定义一组相关类的公共行为和属... 目录一、抽象类的定义1. 语法格式2. 核心特征二、抽象类的核心用途1. 定义公共接口2. 提供默认实

Rust 智能指针的使用详解

《Rust智能指针的使用详解》Rust智能指针是内存管理核心工具,本文就来详细的介绍一下Rust智能指针(Box、Rc、RefCell、Arc、Mutex、RwLock、Weak)的原理与使用场景,... 目录一、www.chinasem.cnRust 智能指针详解1、Box<T>:堆内存分配2、Rc<T>:

Java中的堆和栈示例详解

《Java中的堆和栈示例详解》在Java中,堆(Heap)和栈(Stack)是两种不同的内存区域,本文给大家介绍Java中的堆和栈,结合实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前言二、栈(Stack)三、堆(Heap)四、核心区别五、代码示例六、常见问题七、总结一、前言在Jav

Java Docx4j类库简介及使用示例详解

《JavaDocx4j类库简介及使用示例详解》Docx4j是一个强大而灵活的Java库,非常适合需要自动化生成、处理、转换MicrosoftOffice文档的服务器端或后端应用,本文给大家介绍Jav... 目录1.简介2.安装与依赖3.基础用法示例3.1 创建一个新 DOCX 并添加内容3.2 读取一个已存

C#使用iText获取PDF的trailer数据的代码示例

《C#使用iText获取PDF的trailer数据的代码示例》开发程序debug的时候,看到了PDF有个trailer数据,挺有意思,于是考虑用代码把它读出来,那么就用到我们常用的iText框架了,所... 目录引言iText 核心概念C# 代码示例步骤 1: 确保已安装 iText步骤 2: C# 代码程

C++中处理文本数据char与string的终极对比指南

《C++中处理文本数据char与string的终极对比指南》在C++编程中char和string是两种用于处理字符数据的类型,但它们在使用方式和功能上有显著的不同,:本文主要介绍C++中处理文本数... 目录1. 基本定义与本质2. 内存管理3. 操作与功能4. 性能特点5. 使用场景6. 相互转换核心区别

python pymodbus模块的具体使用

《pythonpymodbus模块的具体使用》pymodbus是一个Python实现的Modbus协议库,支持TCP和RTU通信模式,支持读写线圈、离散输入、保持寄存器等数据类型,具有一定的参考价值... 目录一、详解1、 基础概念2、核心功能3、安装与设置4、使用示例5、 高级特性6、注意事项二、代码示例

一个Java的main方法在JVM中的执行流程示例详解

《一个Java的main方法在JVM中的执行流程示例详解》main方法是Java程序的入口点,程序从这里开始执行,:本文主要介绍一个Java的main方法在JVM中执行流程的相关资料,文中通过代码... 目录第一阶段:加载 (Loading)第二阶段:链接 (Linking)第三阶段:初始化 (Initia