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

 更新时间:2025年09月25日 10:41:30   作者:Q.V.Q  
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_next(); r.next()) {
			std::cout << r.get_text() << std::endl;
		}
	}

	return 0;
}

运行结果如下:

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

3. 添加段落

#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.insert_paragraph_after("This is a new paragraph.");
        }

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

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

    return 0;
}

原始文件如下:

修改文件如下:

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;
}

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;
}

原始文档如下:

修改文档如下:

二、进阶用法

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;
}

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

#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);
                }
            }
        }
    }

    // 遍历表格
    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;
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • C语言的运算符你了解吗

    C语言的运算符你了解吗

    这篇文章主要介绍了C语言中的运算符,本文给大家介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下,希望能给你带来帮助
    2021-08-08
  • C语言程序中递归算法的使用实例教程

    C语言程序中递归算法的使用实例教程

    这篇文章主要介绍了C语言程序中递归算法的使用实例教程,递归经常被用来进行阶乘和比较大小等计算工作,文中举的都是一些基础的例子,需要的朋友可以参考下
    2016-04-04
  • C++之vector内存释放原理

    C++之vector内存释放原理

    这篇文章主要介绍了C++之vector内存释放原理,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • C++中十种内部排序算法的比较分析

    C++中十种内部排序算法的比较分析

    本文给大家分享的是个人写的一段对C++中十种内部排序算法的比较分析的代码,主要在于测试10种排序方法的性能,给大家参考下吧。
    2015-03-03
  • C++中的策略模式浅析

    C++中的策略模式浅析

    策略模式属于C++设计模式中行为模式之一,该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换。本文将通过示例详细讲解这一模式,需要的可以参考一下
    2023-02-02
  • C++11中互斥锁的使用

    C++11中互斥锁的使用

    本文主要介绍了C++11中互斥锁的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-06-06
  • C++ 中cerr和cout的区别实例详解

    C++ 中cerr和cout的区别实例详解

    这篇文章主要介绍了C++ 中cerr和cout的区别实例详解的相关资料,希望通过本文能帮助到大家,让大家理解掌握这部分内容,需要的朋友可以参考下
    2017-09-09
  • 详解C++ new-handler机制

    详解C++ new-handler机制

    这篇文章主要介绍了C++ new-handler机制的相关资料,帮助大家更好的理解和使用c++,感兴趣的朋友可以了解下
    2020-11-11
  • c语言中单引号和双引号的区别(顺利解决从字符串中提取IP地址的困惑)

    c语言中单引号和双引号的区别(顺利解决从字符串中提取IP地址的困惑)

    c语言中的单引号和双引号可是有很大区别的,使用之前一定要了解他们之间到底有什么不同,下面小编就给大家详细的介绍一下吧,对此还不是很了解的朋友可以过来参考下
    2013-07-07
  • C++实现约瑟夫环的循环单链表

    C++实现约瑟夫环的循环单链表

    这篇文章主要为大家详细介绍了C++实现约瑟夫环的循环单链表,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10

最新评论