C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#批量替换Word文本

C#代码实现Word文档文本批量替换(动态填充)

作者:LAYONTHEGROUND

在各类企业级应用中,程序化修改 Word 文档是一个高频需求,Free Spire.Doc for .NET 是一套在无需本地安装 Microsoft Office 环境下直接操作 Word 文档的免费 .NET API,下面我们就来看看如何使用它实现批量替换Word文本吧

在各类企业级应用中,程序化修改 Word 文档是一个高频需求——批量更新合同模板中的占位符、动态生成个性化的报告与报价单、统一标准化文档中的术语表述等。实现这类需求的核心技术挑战在于:Word 文档采用复杂的内置结构存储文本与格式,简单的字符串操作极易破坏文档的格式完整性,导致输出结果无法满足正式应用的标准。

Free Spire.Doc for .NET 是一套在无需本地安装 Microsoft Office 环境下直接操作 Word 文档的免费 .NET API,其 DocumentParagraph 类提供了 ReplaceFindAllString 等多个文本查找与替换的重载方法,支持普通字符串、正则表达式匹配等场景。以下将从基础用法到高级技巧逐步展开。

环境准备

将 Free Spire.Doc 添加到项目中最便捷的方式是通过 NuGet 包管理器。在 Visual Studio 的“管理 NuGet 程序包”中搜索 FreeSpire.Doc 并安装,或在包管理器控制台中执行以下命令:

Install-Package FreeSpire.Doc

安装完成后,在代码文件顶部引入核心命名空间:

using Spire.Doc;
using Spire.Doc.Documents;
using System.Text.RegularExpressions;

基础示例:替换 Word 中的指定文本

用到的免费 .NET 库的核心替换方法是 Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord),该方法在整个文档范围内查找指定的字符串并将其替换为新文本。

参数说明

以下示例演示将文档中的旧公司名称替换为新名称:

public static void BasicReplace(string inputPath, string outputPath)
{
    // 创建 Document 对象并加载文档
    Document document = new Document();
    document.LoadFromFile(inputPath);
    // 执行替换操作:不区分大小写,匹配完整单词
    document.Replace("old_company_name", "NewTech Solutions Inc.", false, true);
    // 保存修改后的文档
    document.SaveToFile(outputPath, FileFormat.Docx);
    document.Close();
}

该方法在替换过程中能够保留原文本的格式与排版,确保文档的其他元素(如图片、表格、页眉页脚等)不受影响。

可选:仅替换首次出现的文本

若业务需求仅需将文档中第一次出现的目标文本进行替换,可在调用 Replace 方法之前将 Document.ReplaceFirst 属性设置为 true

public static void ReplaceFirstInstance(string inputPath, string outputPath)
{
    Document document = new Document();
    document.LoadFromFile(inputPath);
    // 将替换模式设置为仅替换第一个匹配项
    document.ReplaceFirst = true;
    document.Replace("placeholder", "actual value", false, true);
    document.SaveToFile(outputPath, FileFormat.Docx);
    document.Close();
}

进阶:使用正则表达式进行模式匹配替换

对于需要匹配某种模式而非固定字符串的场景(例如替换所有占位符 {{...}}、匹配特定格式的编号等),可以使用 Document.Replace(Regex regex, string newValue) 方法的重载版本。

以下示例展示如何将文档中所有由花括号包裹的占位符替换为指定的值:

using System.Text.RegularExpressions;
public static void RegexReplace(string inputPath, string outputPath)
{
    Document document = new Document();
    document.LoadFromFile(inputPath);
    // 匹配形如 {{placeholder}} 的占位符模式
    Regex placeholderRegex = new Regex(@"\{\{.*?\}\}");
    // 将所有匹配的占位符替换为目标字符串
    document.Replace(placeholderRegex, "replacement text");
    document.SaveToFile(outputPath, FileFormat.Docx);
    document.Close();
}

更复杂的使用场景中,还可调用 Replace(Regex, TextSelection) 等重载变体进行带格式的替换操作。

扩展:查找文本并做进一步处理(查找高亮)

除了直接替换,Document.FindAllString 方法可以获取所有匹配的 TextSelection 对象集合,便于在替换前对匹配结果进行预览、统计,或在替换后应用格式设置(如高亮显示)。

using System.Drawing;
public static void FindAndHighlight(string inputPath, string outputPath)
{
    Document document = new Document();
    document.LoadFromFile(inputPath);
    // 查找所有匹配的文本
    TextSelection[] selections = document.FindAllString("keyword", false, true);
    foreach (TextSelection selection in selections)
    {
        // 将匹配的文本设置为高亮黄色
        selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
    }
    document.SaveToFile(outputPath, FileFormat.Docx);
    document.Close();
}

知识扩展

在 .NET 项目中实现 Word 文档的自动化文本替换,不需要操作界面,有几种成熟的方案。根据项目是内部工具还是商业产品,以及预算和文档规模,选择会有所不同。

基础替换:简单字符串替换

最直接的需求是把文档中的占位符(如 {{Name}})替换成具体值。

using Spire.Doc;
Document doc = new Document("Template.docx");
// 在整个文档范围内替换
// 参数:目标文本、新文本、是否区分大小写、是否仅匹配完整单词
doc.Replace("{{PartyA}}", "张三", true, true);
doc.Replace("{{PartyB}}", "李四", true, true);
doc.SaveToFile("Output.docx", FileFormat.Docx);

如果你的文档中没有使用特殊的占位符标记(如 {{...}}),还可以结合正则表达式做更灵活的匹配:例如 new Regex(@"\{[^\}]+\}") 可以匹配所有被花括号包裹的文本。

正则匹配:批量匹配模式化占位符

对于模板中存在大量相似占位符的情况,正则表达式是更高效的选择。

using Spire.Doc;
using System.Text.RegularExpressions;
Document doc = new Document("Template.docx");
// 匹配所有被花括号包围的占位符,如 {{Name}}、{{Date}}、{{Amount}}
Regex placeholderPattern = new Regex(@"\{\{(.*?)\}\}");
doc.Replace(placeholderPattern, "[已替换]");
doc.SaveToFile("Output.docx", FileFormat.Docx);

在替换之前,你还可以用 FindAllString 预先获取所有匹配项,进行预览或统计:

csharp

TextSelection[] matches = doc.FindAllString(placeholderPattern, true);
Console.WriteLine($"找到 {matches.Length} 处占位符");

分段处理:应对大文档的内存优化

如果文档较大,可以采用分段处理的方式,避免一次性加载整个文档。经过分段处理后,100 页合同的内存峰值可从 412 MB 降至约 98 MB。

using Spire.Doc;
Document doc = new Document("LargeDocument.docx");
foreach (Section section in doc.Sections)
{
    foreach (Paragraph para in section.Paragraphs)
    {
        para.Replace("{{CompanyName}}", "某某科技公司", true, true);
    }
    // 每处理 5 个 Section 释放一次缓存,降低内存峰值
    if (section.Index % 5 == 0)
        doc.ClearCache();
}
doc.SaveToFile("Output.docx", FileFormat.Docx);

Interop方式:依赖Word环境

如果项目中必须使用 Interop,请务必做好资源释放,否则容易导致 Word 进程残留。

using Word = Microsoft.Office.Interop.Word;
var wordApp = new Word.Application();
wordApp.Visible = false;
try
{
    Word.Document doc = wordApp.Documents.Open(@"C:\Template.docx");
    wordApp.Selection.Find.ClearFormatting();
    wordApp.Selection.Find.Replacement.ClearFormatting();
    object findText = "{{Name}}";
    object replaceWith = "张三";
    object replaceAll = Word.WdReplace.wdReplaceAll;
    wordApp.Selection.Find.Execute(ref findText, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing, ref missing,
        ref missing, ref replaceWith, ref replaceAll);
    doc.SaveAs2(@"C:\Output.docx");
    doc.Close();
}
finally
{
    wordApp.Quit();
}

批量处理多个文档与动态填充

实际业务中,最典型的场景是:从数据库或 Excel 中读取多组数据,分别填充到多个 Word 模板中,生成一系列文档。

using Spire.Doc;
public class OrderData
{
    public string OrderId { get; set; }
    public string CustomerName { get; set; }
    public string ProductName { get; set; }
    public decimal Amount { get; set; }
    public DateTime Date { get; set; }
}
public void BatchGenerateOrders(string templatePath, List<OrderData> orders, string outputDir)
{
    for (int i = 0; i < orders.Count; i++)
    {
        var order = orders[i];
        Document doc = new Document(templatePath);
        // 逐一替换占位符
        doc.Replace("{{OrderId}}", order.OrderId, true, true);
        doc.Replace("{{CustomerName}}", order.CustomerName, true, true);
        doc.Replace("{{ProductName}}", order.ProductName, true, true);
        doc.Replace("{{Amount}}", order.Amount.ToString("F2"), true, true);
        doc.Replace("{{Date}}", order.Date.ToString("yyyy-MM-dd"), true, true);
        string outputPath = Path.Combine(outputDir, $"Order_{order.OrderId}.docx");
        doc.SaveToFile(outputPath, FileFormat.Docx);
        Console.WriteLine($"已生成: {outputPath}");
    }
}

更灵活的做法是使用 Dictionary<string, string> 建立映射表,然后遍历所有映射项统一替换,方便新增/修改占位符:

var replacements = new Dictionary<string, string>
{
    { "{{CustomerName}}", "张三" },
    { "{{ProductName}}", "笔记本电脑" },
    { "{{Amount}}", "4999.00" }
};
Document doc = new Document("Template.docx");
foreach (var kvp in replacements)
{
    doc.Replace(kvp.Key, kvp.Value, true, true);
}
doc.SaveToFile("Output.docx", FileFormat.Docx);

总结

本文提供了一套较为完整的 Word 文档文本替换示例:从基础的 Replace 字符串替换、仅替换首次出现、正则表达式模式匹配,到 FindAllString 查找并做格式调整,基本覆盖了 .NET 环境下 Word 文档批量处理的常见需求。

在实际项目中,建议根据文档规模和业务复杂度选择合适的替换策略;对于需要格式保留的复杂内容场景,可进一步利用其他重载或自行封装处理。

到此这篇关于C#代码实现Word文档文本批量替换(动态填充)的文章就介绍到这了,更多相关C#批量替换Word文本内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文