环境准备
将 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),该方法在整个文档范围内查找指定的字符串并将其替换为新文本。
参数说明:
matchString:要查找的目标文本newValue:替换后的新文本caseSensitive:是否区分大小写(true为区分,false为不区分)wholeWord:是否仅匹配完整单词(true时仅替换独立的完整单词)
以下示例演示将文档中的旧公司名称替换为新名称:
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(); }