很多项目需要把多份 Word 文档汇总到一份成品里:例如把多个章节的材料拼成一个报告、把不同来源的稿件合并后交付。与此同时,"合并后格式是否正常、分页是否符合预期、代码是否足够简洁"往往决定了方案能否落地。
下面介绍两种常见的合并策略,均使用 Spire.Doc for .NET 实现:
- 方法一 :将后文档整体追加到前文档后面(通常带来"从新页开始"的整体插入体验)
- 方法二 :遍历后文档的 Section,将其内容对象克隆后追加到前文档最后一个 Section,适合更精细的结构控制
Spire.Doc 用途与安装方法(Section 简介)
Spire.Doc 是用于 .NET 读取、编辑与生成 Word 文档(DOC/DOCX)的组件库。它提供面向文档结构的 API,例如加载文档、插入内容、遍历 Section/Body/对象集合、复制文档元素、保存为 DOCX 等。相比自行解析 docx 压缩包与 XML,使用它可以显著降低开发成本。
安装方式(推荐 NuGet):
- 在 Visual Studio 打开项目
- 右键项目 → 管理 NuGet 程序包
- 搜索并安装 Spire.Doc for .NET
- 在代码中引用命名空间:
using Spire.Doc;
完成安装后,就能直接通过 Document 类来加载与操作 Word 文件。
方法一:整体插入到末尾(从新页开始的常见效果)
当目标是"把 Doc2 作为一个整体接到 Doc1 后面",同时希望合并结果更接近 Word 中的"插入文档/追加内容"的直观体验时,可以使用 InsertTextFromFile。
实现思路:
- 创建
Document对象作为承载文档 - 加载主文档(Doc1)
- 将另一个 Word 文件(Doc2)插入到主文档后
- 保存为新的合并文件
示例代码:
using Spire.Doc;
namespace MergeWord
{
class Program
{
static void Main(string[] args)
{
// Create a Document instance
Document document = new Document();
// Load the original Word document
document.LoadFromFile("Doc1.docx", FileFormat.Docx);
// Insert another Word document entirely to the original document
document.InsertTextFromFile("Doc2.docx", FileFormat.Docx);
// Save the result document
document.SaveToFile("MergedWord.docx", FileFormat.Docx);
}
}
}
这种方式的特点
- 代码量少、开发速度快
- 更偏"整体追加",适合按文档边界合并
- 对 Section 级别结构的细节控制相对少,但通常足够满足常见汇总需求
方法二:追加到第一个文档最后一个 Section(结构更可控)
如果合并要求更精细,例如尽量让内容与前文档"同节连续",或者需要把后文档的内容对象逐个追加到前文档末尾,那么可采用第二种方案:遍历后文档的 Sections,再遍历每个 Section 的 Body.ChildObjects,将对象 Clone() 后加入前文档最后一个 Section。
实现思路:
- 分别加载
doc1与doc2 - 遍历
doc2.Sections - 对每个 section,遍历其
section.Body.ChildObjects - 将克隆后的对象添加到
doc1.LastSection.Body.ChildObjects - 保存
doc1作为合并结果
示例代码:
using Spire.Doc;
namespace MergeWord
{
class Program
{
static void Main(string[] args)
{
// Load two Word documents
Document doc1 = new Document("Doc1.docx");
Document doc2 = new Document("Doc2.docx");
// Loop through the second document to get all the sections
foreach (Section section in doc2.Sections)
{
// Loop through the sections of the second document to get their child objects
foreach (DocumentObject obj in section.Body.ChildObjects)
{
// Get the last section of the first document
Section lastSection = doc1.LastSection;
// Add all child objects to the last section of the first document
lastSection.Body.ChildObjects.Add(obj.Clone());
}
}
// Save the result document
doc1.SaveToFile("MergeDocuments.docx", FileFormat.Docx);
}
}
}
这种方式的特点
- 更接近"把内容对象直接拼到最后一节里"
- 通过
Clone()进行对象复制,避免直接引用引发的问题 - 适合处理包含多节结构、页眉页脚/分页规则等更复杂情况(具体效果仍需根据模板而定)
如何选择?
- 只想快速合并,并希望结果接近"从新页开始追加"的直观效果:方法一更省事。
- 需要更强的结构控制,把后文档内容追加到前文档最后一个 Section:方法二更贴合需求。
如果你的文档模板包含页眉页脚、不同方向页面(横/竖版)或复杂节配置,建议优先用方法二做验证;如果只是普通文本与表格拼接,方法一通常更快更稳定。