文本替换只能写入字符串,无法保留段落、表格、列表或域结构。合同、项目章程与报告模板中的占位符,往往需要替换为整段说明、一张表格、一段带格式的 HTML,或者一个可以自动更新的日期域。此类操作需要先定位占位符,再在段落或正文层级插入新的文档对象。
Spire.Doc for C++ 提供 Document->Replace()、Paragraph->AppendHTML() 与正文对象集合的插入方法完成富内容替换。查找返回 TextSelection,通过 GetAsOneRange() 取得占位符所在的 TextRange,即可读取所在段落与下标;插入表格、域或克隆段落时,以该下标为基准。全部处理在本地进程中完成,文档无需上传到任何服务。
本文介绍四个功能点:
示例使用《项目章程》模板(ProjectCharter.docx),其中预留了四个方括号占位符:
| 占位符 | 替换为 | 主要调用 |
|---|---|---|
[PROJECT_OVERVIEW] |
另一份 Word 文档 | Document->Replace() |
[DELIVERY_SCOPE] |
HTML 片段 | Paragraph->AppendHTML() 与 ChildObjects->Insert() |
[MILESTONES] |
表格 | Section->AddTable() 与 ChildObjects->Insert() |
[SIGN_DATE] |
DATE 域 | Field 与 FieldMark |

模板中的前三个占位符各占一个独立段落,签署日期则位于签署句中间,前后还有“签署日期:”与“(审批后生效)”两段文字。替换为文档、HTML 与表格的示例按段落边界处理,替换为域的示例只移除占位符范围,保留同一段落中的其余文字。
安装 Spire.Doc for C++
有两种方法可以将 Spire.Doc for C++ 集成到您的应用程序中。一种方法是通过 NuGet 安装,另一种方法是从我们的网站下载包并将库复制到您的程序中。通过 NuGet 安装更简单,也更推荐使用。
- 在 Visual Studio 中打开“NuGet 包管理器”,搜索并安装
Spire.Doc.Cpp。 - 或在项目所在目录执行
nuget install Spire.Doc.Cpp,再将包中的include与lib目录加入项目。
集成后的项目需要引用对应的动态库,并确保运行目录中存在 SpireDocCpp.dll、Spire.Doc.Base.dll、libSkiaSharp.dll 与 libHarfBuzzSharp.dll。更详细的配置说明请参考如何将 Spire.Doc for C++ 集成到 C++ 程序中。
示例使用 14.9.x 版本,字符串类型为 UTF-8 窄字符串。包含中文的源文件应以 UTF-8 编码保存,并在 MSVC 中启用 /utf-8 编译选项,字符串字面量中的中文才能被正确识别。
用 Word 文档替换文本
用 Word 文档替换文本,可以调用 Document->Replace() 将匹配文本替换为另一份文档的内容。传入来源文档时,方法签名为 int Replace(const std::string& matchString, intrusive_ptr<Document> matchDoc, bool caseSensitive, bool wholeWord),返回值是实际替换的处数。
| 参数 | 含义 |
|---|---|
matchString |
要查找的占位符文本 |
matchDoc |
用于替换的文档对象 |
caseSensitive |
是否区分大小写 |
wholeWord |
是否只匹配完整单词 |
具体操作步骤如下。
- 创建 Document 对象。
- 使用 Document->LoadFromFile() 方法加载模板文档。
- 创建另一个 Document 对象,加载用于替换的 Word 文档。
- 调用 Document->Replace(),以
matchDoc指定替换内容。 - 使用 Document->SaveToFile() 方法保存结果文档。
用 Word 文档替换文本的代码如下。
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
int main()
{
//指定输入文件路径
string inputFilePath = "ProjectCharter.docx";
string overviewFilePath = "ProjectOverview.docx";
//指定输出文件路径和名称
string outputPath = "Output/";
string outputFile = outputPath + "ReplaceWithDocument.docx";
//创建 Document 对象并加载模板
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFilePath);
//加载用于替换的文档
intrusive_ptr<Document> overview = new Document();
overview->LoadFromFile(overviewFilePath);
//将占位符替换为另一份文档的内容
int count = document->Replace("[PROJECT_OVERVIEW]", overview, false, false);
SetConsoleOutputCP(CP_UTF8);
cout << "Replaced: " << count << endl;
//保存结果文件
document->SaveToFile(outputFile, FileFormat::Docx2013);
overview->Close();
document->Close();
return 0;
}
示例输出为 Replaced: 1,模板中的 [PROJECT_OVERVIEW] 被《项目概述》文档的标题、段落与项目符号列表替换,模板其余内容保持不变:

返回值是替换处数
Document->Replace() 返回整篇文档中实际替换的次数,而不是布尔值。示例模板中只有一个 [PROJECT_OVERVIEW],因此返回 1。批量处理多份模板时,可以累加返回值,或在替换数为 0 时记录日志,排查占位符拼写与匹配参数。
匹配参数与占位符写法
后两个参数分别控制区分大小写与全词匹配。示例使用 false, false,忽略大小写,并允许匹配出现在更长字符串中的占位符。占位符不限于方括号,@@OVERVIEW@@、{{milestones}} 等写法同样可用;方括号醒目且不易与正文冲突,便于在模板中肉眼核对。
来源文档的内容连同格式一起插入
替换时,来源文档的段落、字符格式与列表结构会复制到目标位置,来源文档本身不会被修改。示例在替换完成后调用 overview->Close() 释放资源。若只需要插入来源文档的部分段落,可以不使用 Replace():先用 FindString() 定位占位符,取得所在段落与正文下标,再遍历来源文档的节与段落,把指定段落克隆后插入该下标,最后移除占位符范围。插入的段落保留来源文档的格式,适合在插入前逐段筛选或调整。
用 HTML 片段替换文本
用 HTML 片段替换文本,需要先由 Paragraph->AppendHTML() 将 HTML 解析为 Word 对象,再写入段落所属的正文。解析结果可能包含多个段落与列表项,示例先在临时节中生成这些对象,收集为数组,再把它们插入占位符所在位置。占位符位于段首、段尾或段落中间时,处理方式不同。
| 占位符位置 | 处理方式 |
|---|---|
段首(index == 0) |
移除段落首个对象,在原段落位置插入替换对象 |
段尾(index == count - 1) |
移除段落末尾对象,在段落之后插入替换对象 |
| 段落中间 | 克隆原段落,拆分占位符前后的内容,在中间插入替换对象 |
具体操作步骤如下。
- 创建 Document 对象,加载模板文档。
- 使用
ifstream读取 HTML 文件,得到 UTF-8 字符串。 - 调用 Document->AddSection() 创建临时节,在临时段落中调用 Paragraph->AppendHTML() 解析 HTML。
- 遍历临时节正文,收集生成的对象。
- 调用 Document->FindAllString() 查找全部占位符,记录所在段落、范围与下标。
- 按从后往前的顺序插入替换对象,并移除占位符范围。
- 调用 SectionCollection->Remove() 删除临时节,保存结果文档。
用 HTML 片段替换文本的代码如下。除前述头文件外,还需引入 Spire/Doc/Body.h、Spire/Doc/DocumentObject.h、Spire/Doc/Collections/DocumentObjectCollection.h、Spire/Doc/Documents/Paragraph.h、Spire/Doc/Documents/TextSelection.h、Spire/Doc/Fields/TextRange.h、Spire/Doc/Section.h 与 Spire/Doc/common/h/Object.h。
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Body.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/common/h/Object.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
struct PlaceholderLocation
{
intrusive_ptr<TextRange> range;
intrusive_ptr<Paragraph> paragraph;
intrusive_ptr<Body> body;
int paragraphIndex;
int rangeIndex;
};
//将收集到的对象插入占位符所在位置
void ReplaceWithHTML(PlaceholderLocation location,
vector<intrusive_ptr<DocumentObject>>& replacement)
{
int index = location.rangeIndex;
intrusive_ptr<Paragraph> paragraph = location.paragraph;
intrusive_ptr<Body> sectionBody = location.body;
int replacementIndex = -1;
if (index == 0)
{
//段首:移除首个对象,在段落位置插入
paragraph->GetChildObjects()->RemoveAt(0);
replacementIndex = sectionBody->GetChildObjects()->IndexOf(paragraph);
}
else if (index == paragraph->GetChildObjects()->GetCount() - 1)
{
//段尾:移除末尾对象,在段落之后插入
paragraph->GetChildObjects()->RemoveAt(index);
replacementIndex = location.paragraphIndex + 1;
}
else
{
//段中:拆分原段落,占位符之前的内容留在原段落
intrusive_ptr<Paragraph> tail =
Object::Dynamic_cast<Paragraph>(paragraph->Clone());
while (paragraph->GetChildObjects()->GetCount() > index)
{
paragraph->GetChildObjects()->RemoveAt(index);
}
int stop = index + 1;
for (int i = 0; i < stop; i++)
{
tail->GetChildObjects()->RemoveAt(0);
}
sectionBody->GetChildObjects()->Insert(location.paragraphIndex + 1, tail);
replacementIndex = location.paragraphIndex + 1;
}
for (size_t i = 0; i < replacement.size(); i++)
{
sectionBody->GetChildObjects()->Insert(replacementIndex + (int)i,
replacement[i]->Clone());
}
}
int main()
{
//指定输入文件路径
string inputFilePath = "ProjectCharter.docx";
string htmlFilePath = "ScopeSnippet.html";
//指定输出文件路径和名称
string outputPath = "Output/";
string outputFile = outputPath + "ReplaceWithHtml.docx";
//读取 HTML 片段
ifstream htmlFile(htmlFilePath);
string html((istreambuf_iterator<char>(htmlFile)), istreambuf_iterator<char>());
//加载模板
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFilePath);
//在临时节中解析 HTML,并收集生成的对象
vector<intrusive_ptr<DocumentObject>> replacement;
intrusive_ptr<Section> tempSection = document->AddSection();
intrusive_ptr<Paragraph> holder = tempSection->AddParagraph();
holder->AppendHTML(html);
for (int i = 0; i < tempSection->GetBody()->GetChildObjects()->GetCount(); i++)
{
replacement.push_back(tempSection->GetBody()->GetChildObjects()->GetItem(i));
}
//记录每个占位符的位置
vector<PlaceholderLocation> locations;
vector<intrusive_ptr<TextSelection>> selections =
document->FindAllString("[DELIVERY_SCOPE]", false, false);
for (intrusive_ptr<TextSelection> selection : selections)
{
PlaceholderLocation location;
location.range = selection->GetAsOneRange();
location.paragraph = location.range->GetOwnerParagraph();
location.body = location.paragraph->GetOwnerTextBody();
location.paragraphIndex = location.body->GetChildObjects()->IndexOf(location.paragraph);
location.rangeIndex = location.paragraph->GetChildObjects()->IndexOf(location.range);
locations.push_back(location);
}
//从后往前处理,避免前面的下标因插入而偏移
sort(locations.begin(), locations.end(),
[](const PlaceholderLocation& a, const PlaceholderLocation& b)
{
if (a.paragraphIndex != b.paragraphIndex)
return a.paragraphIndex > b.paragraphIndex;
return a.rangeIndex > b.rangeIndex;
});
for (PlaceholderLocation location : locations)
{
ReplaceWithHTML(location, replacement);
}
//删除临时节
document->GetSections()->Remove(tempSection);
//保存结果文件
document->SaveToFile(outputFile, FileFormat::Docx2013);
document->Close();
return 0;
}
示例中的 ScopeSnippet.html 包含一个三级标题、一段说明与四项列表。执行后,[DELIVERY_SCOPE] 被替换为带标题、说明与项目符号列表的 HTML 内容:

HTML 支持的范围
Paragraph->AppendHTML() 支持常见的块级与行内元素,包括标题、段落、列表、表格、加粗、斜体与行内样式。外部样式表、脚本与复杂的 CSS 定位不会生效,页面布局会按 Word 的段落与表格模型重新计算。需要精确控制版式时,直接构造 Word 对象比依赖 HTML 更可靠。
多个占位符按从后往前的顺序替换
插入替换对象会改变后续正文对象的下标。示例先收集全部占位符的位置,按段落下标与范围内标从大到小排序,再依次替换。这样,尚未处理的占位符位置不会受到已插入内容的影响。若按从前往后的顺序处理,后续下标会整体后移,容易插错位置。
占位符位于段落中间时需要拆分段落
段首与段尾的处理只移除占位符所在对象,再插入替换内容;段落中间的情况则先克隆原段落,把占位符之后的对象留在克隆段落中,再从原段落末尾删除,最后在两者之间插入替换对象。示例模板中的 [DELIVERY_SCOPE] 独占一段,走的是段首分支;改写模板后若占位符与正文同处一段,其余分支仍然适用。
用表格替换文本
用表格替换文本以段落为边界:先查找占位符,取得所在段落与正文下标,创建并填充表格,再移除原段落,把表格插入到同一位置。表格的列宽、表头底色、隔行底色与单元格内边距都可以在插入前设置。
具体操作步骤如下。
- 创建 Document 对象,加载模板文档。
- 调用 Document->FindString() 定位占位符,取得所在段落与正文下标。
- 调用 Section->AddTable() 创建表格,用 Table->ResetCells() 设置行列数并填充内容。
- 调用 TableRow->SetIsHeader() 标记表头,用 CellFormat->GetShading() 设置单元格底色。
- 移除占位符所在段落,在相同下标处插入表格。
- 使用 Document->SaveToFile() 方法保存结果文档。
用表格替换文本的代码如下。
#include <iostream>
#include <string>
#include <vector>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Body.h"
#include "Spire/Doc/Collections/CellCollection.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/ParagraphCollection.h"
#include "Spire/Doc/Collections/RowCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/HorizontalAlignment.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/Fields/Shapes/Shading.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CellFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Formatting/Paddings.h"
#include "Spire/Doc/Formatting/ParagraphFormat.h"
#include "Spire/Doc/LineSpacingRule.h"
#include "Spire/Doc/PreferredWidth.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/Table.h"
#include "Spire/Doc/TableCell.h"
#include "Spire/Doc/TableRow.h"
#include "Spire/Doc/WidthType.h"
#include "Spire/Doc/common/h/Color.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;
//统一单元格段落的行距与段后间距,避免表格行高过大
void SetCellParagraphSpacing(intrusive_ptr<Paragraph> paragraph)
{
intrusive_ptr<ParagraphFormat> format = paragraph->GetFormat();
format->SetBeforeSpacing(0);
format->SetAfterSpacing(0);
format->SetLineSpacingRule(LineSpacingRule::Exactly);
format->SetLineSpacing(16.0f);
}
int main()
{
//指定输入文件路径
string inputFilePath = "ProjectCharter.docx";
//指定输出文件路径和名称
string outputPath = "Output/";
string outputFile = outputPath + "ReplaceWithTable.docx";
//加载模板
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFilePath.c_str());
//定位占位符,取得所在段落与正文下标
intrusive_ptr<TextSelection> selection =
document->FindString("[MILESTONES]", false, false);
intrusive_ptr<TextRange> range = selection->GetAsOneRange();
intrusive_ptr<Paragraph> paragraph = range->GetOwnerParagraph();
intrusive_ptr<Body> body = paragraph->GetOwnerTextBody();
int paragraphIndex = body->GetChildObjects()->IndexOf(paragraph);
//创建 5 行 3 列的表格
intrusive_ptr<Section> section = document->GetSections()->GetItem(0);
intrusive_ptr<Table> table = section->AddTable(true);
table->SetPreferredWidth(new PreferredWidth(WidthType::Percentage, 100));
table->ResetCells(5, 3);
vector<vector<string>> data =
{
{"阶段", "计划完成", "交付物"},
{"需求确认", "2026-11-20", "需求规格说明书"},
{"设备到货", "2026-12-15", "12 台机器人及充电桩"},
{"系统联调", "2027-01-20", "调度系统与 WMS 接口"},
{"整体验收", "2027-03-15", "验收报告与运维移交"},
};
intrusive_ptr<CharacterFormat> characterFormat = new CharacterFormat(document);
characterFormat->SetFontName("微软雅黑");
characterFormat->SetFontNameFarEast("微软雅黑");
//表头:深蓝底、白色加粗文字
intrusive_ptr<TableRow> headerRow = table->GetRows()->GetItem(0);
headerRow->SetIsHeader(true);
for (int c = 0; c < 3; c++)
{
intrusive_ptr<TableCell> cell = headerRow->GetCells()->GetItem(c);
cell->GetCellFormat()->GetPaddings()->SetAll(4.0f);
cell->GetCellFormat()->GetShading()->SetBackgroundPatternColor(
Color::FromArgbRGB(31, 56, 100));
intrusive_ptr<Paragraph> p = cell->AddParagraph();
SetCellParagraphSpacing(p);
p->GetFormat()->SetHorizontalAlignment(HorizontalAlignment::Center);
intrusive_ptr<TextRange> textRange = p->AppendText(data[0][c]);
textRange->GetCharacterFormat()->SetBold(true);
textRange->GetCharacterFormat()->SetTextColor(Color::GetWhite());
textRange->ApplyCharacterFormat(characterFormat);
}
//数据行:隔行浅色底
for (int r = 1; r < (int)data.size(); r++)
{
intrusive_ptr<TableRow> row = table->GetRows()->GetItem(r);
for (int c = 0; c < 3; c++)
{
intrusive_ptr<TableCell> cell = row->GetCells()->GetItem(c);
cell->GetCellFormat()->GetPaddings()->SetAll(4.0f);
if (r % 2 == 0)
{
cell->GetCellFormat()->GetShading()->SetBackgroundPatternColor(
Color::FromArgbRGB(242, 246, 251));
}
intrusive_ptr<Paragraph> p = cell->AddParagraph();
SetCellParagraphSpacing(p);
if (c == 1)
{
p->GetFormat()->SetHorizontalAlignment(HorizontalAlignment::Center);
}
p->AppendText(data[r][c])->ApplyCharacterFormat(characterFormat);
}
}
//移除占位符段落,在原位置插入表格
body->GetChildObjects()->Remove(paragraph);
body->GetChildObjects()->Insert(paragraphIndex, table);
//保存结果文件
document->SaveToFile(outputFile, FileFormat::Docx2013);
document->Close();
return 0;
}
执行后,[MILESTONES] 所在段落被移除,同一位置出现 5 行 3 列的里程碑表格:

表格替换会移除整个段落
示例中的占位符独占一个段落,因此可以整体移除该段落并插入表格。若段落中还有同级文字,不能直接移除段落,应先拆分:保留占位符之前的内容,把占位符之后的文字移到新段落,再在两者之间插入表格。否则,段落中的其余文字会随段落一起丢失。
表头、隔行底色与单元格内边距
TableRow->SetIsHeader(true) 将首行标记为表头,跨页时会重复显示。单元格底色通过 CellFormat->GetShading()->SetBackgroundPatternColor() 设置,表头使用深蓝色,数据行按奇偶行设置浅色,可以在文档中形成清晰的横向分隔。CellFormat->GetPaddings()->SetAll() 为单元格留出内边距,避免文字贴近边框。
行高由段落格式决定
新建表格的单元格段落会继承文档的默认样式。若模板默认段落在段后保留间距、行距为 1.5 倍,表格行高会明显大于模板中已有表格。示例通过 ParagraphFormat 将段前与段后间距清零,并把行距设为固定 16 磅,使插入的表格与文档整体版式一致。列宽由 PreferredWidth 与单元格内容共同决定,示例将表格宽度设为页面宽度的 100%。
用域替换文本
用域替换文本需要构造域代码与域结果。示例将 [SIGN_DATE] 替换为 DATE 域,域代码使用 yyyy年M月d日 格式,打开文档或更新域后显示当天日期。插入域需要三个对象:Field 本身、FieldSeparator 标记与 FieldEnd 标记。
| 对象 | 作用 |
|---|---|
Field |
定义域类型与域代码 |
FieldMark + FieldMarkType::FieldSeparator |
分隔域代码与域结果 |
FieldMark + FieldMarkType::FieldEnd |
结束域 |
具体操作步骤如下。
- 创建 Document 对象,加载模板文档。
- 调用 Document->FindString() 定位占位符,取得所在段落与范围内标。
- 创建 Field 对象,用 Field->SetType() 设置类型为
FieldDate,用 Field->SetCode() 设置日期域代码。 - 依次插入
Field、FieldSeparator与FieldEnd,再移除占位符范围。 - 设置 Document->SetIsUpdateFields(),保存结果文档。
用域替换文本的代码如下。
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/FieldMarkType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/FieldType.h"
#include "Spire/Doc/Fields/Field.h"
#include "Spire/Doc/Fields/FieldMark.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;
void SetParagraphTextFont(intrusive_ptr<Paragraph> paragraph, const string& fontName)
{
intrusive_ptr<DocumentObjectCollection> childObjects = paragraph->GetChildObjects();
for (int i = 0; i < childObjects->GetCount(); i++)
{
intrusive_ptr<DocumentObject> child = childObjects->GetItem(i);
// 段落中还有域、书签、图片等非文本子对象,只处理 TextRange
if (child->GetDocumentObjectType() != DocumentObjectType::TextRange)
continue;
intrusive_ptr<TextRange> range = Object::Dynamic_cast<TextRange>(child);
if (range == nullptr)
continue;
// FontName 管西文,FarEast 管中文,两者都设可避免主题字体回退
range->GetCharacterFormat()->SetFontName(fontName);
range->GetCharacterFormat()->SetFontNameFarEast(fontName);
}
}
int main()
{
//指定输入文件路径
string inputFilePath = "ProjectCharter.docx";
//指定输出文件路径和名称
string outputPath = "Output/";
string outputFile = outputPath + "ReplaceWithField.docx";
//加载模板
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFilePath);
//定位占位符
intrusive_ptr<TextSelection> selection = document->FindString("[SIGN_DATE]", false, false);
intrusive_ptr<TextRange> range = selection->GetAsOneRange();
intrusive_ptr<Paragraph> paragraph = range->GetOwnerParagraph();
int rangeIndex = paragraph->GetChildObjects()->IndexOf(range);
//创建 DATE 域,格式为“2026年11月25日”
intrusive_ptr<Field> dateField = new Field(document);
dateField->SetType(FieldType::FieldDate);
dateField->SetCode("DATE \\@ \"yyyy年M月d日\"");
//依次插入域、分隔标记与结束标记
paragraph->GetChildObjects()->Insert(rangeIndex, dateField);
intrusive_ptr<FieldMark> separator = new FieldMark(document, FieldMarkType::FieldSeparator);
paragraph->GetChildObjects()->Insert(rangeIndex + 1, separator);
intrusive_ptr<FieldMark> end = new FieldMark(document, FieldMarkType::FieldEnd);
paragraph->GetChildObjects()->Insert(rangeIndex + 2, end);
//移除占位符,占位符之后的文字保持原位
paragraph->GetChildObjects()->Remove(range);
SetParagraphTextFont(paragraph, "微软雅黑");
//更新域,使保存后的文件显示域结果
document->SetIsUpdateFields(true);
//保存结果文件
document->SaveToFile(outputFile, FileFormat::Docx2013);
document->Close();
return 0;
}
执行后,[SIGN_DATE] 被替换为当天日期,占位符之后的“(审批后生效)”仍保留在日期之后:

域代码中的反斜杠与引号
Field->SetCode() 接收的是域代码字符串。示例中的 DATE \\@ "yyyy年M月d日" 在 C++ 字符串字面量中写作双反斜杠,实际域代码为 DATE \@ "yyyy年M月d日"。引号内的格式串由 Word 解释,yyyy 表示四位年份,M 与 d 分别表示不补零的月份与日期。需要固定显示格式时,可在格式串中补充 MM 与 dd。
保留占位符之后的文字
插入域时,先把 Field、分隔标记与结束标记依次插入占位符之前,再移除占位符范围。这样,占位符之后的文字仍留在原段落中,不会随占位符一起删除。若先移除占位符再插入,范围内标会发生变化,后续文字的位置也需要重新计算。
更新域后显示结果
Field 只定义域的类型与代码,显示结果由域更新产生。示例在保存前设置 SetIsUpdateFields(true),Word 或 WPS 打开文件时会更新域,显示当天的日期;若文件由其他程序读取且未触发更新,可能仍显示域代码或缓存结果。也可以在 Word 中选中域后按 F9 手动更新。
申请临时 License
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。







