C#代碼實現(xiàn)Word文檔文本批量替換(動態(tài)填充)
在各類企業(yè)級應(yīng)用中,程序化修改 Word 文檔是一個高頻需求——批量更新合同模板中的占位符、動態(tài)生成個性化的報告與報價單、統(tǒng)一標(biāo)準(zhǔn)化文檔中的術(shù)語表述等。實現(xiàn)這類需求的核心技術(shù)挑戰(zhàn)在于:Word 文檔采用復(fù)雜的內(nèi)置結(jié)構(gòu)存儲文本與格式,簡單的字符串操作極易破壞文檔的格式完整性,導(dǎo)致輸出結(jié)果無法滿足正式應(yīng)用的標(biāo)準(zhǔn)。
Free Spire.Doc for .NET 是一套在無需本地安裝 Microsoft Office 環(huán)境下直接操作 Word 文檔的免費 .NET API,其 Document 和 Paragraph 類提供了 Replace 和 FindAllString 等多個文本查找與替換的重載方法,支持普通字符串、正則表達(dá)式匹配等場景。以下將從基礎(chǔ)用法到高級技巧逐步展開。
環(huán)境準(zhǔn)備
將 Free Spire.Doc 添加到項目中最便捷的方式是通過 NuGet 包管理器。在 Visual Studio 的“管理 NuGet 程序包”中搜索 FreeSpire.Doc 并安裝,或在包管理器控制臺中執(zhí)行以下命令:
Install-Package FreeSpire.Doc
安裝完成后,在代碼文件頂部引入核心命名空間:
using Spire.Doc; using Spire.Doc.Documents; using System.Text.RegularExpressions;
基礎(chǔ)示例:替換 Word 中的指定文本
用到的免費 .NET 庫的核心替換方法是 Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord),該方法在整個文檔范圍內(nèi)查找指定的字符串并將其替換為新文本。
參數(shù)說明:
matchString:要查找的目標(biāo)文本newValue:替換后的新文本caseSensitive:是否區(qū)分大小寫(true為區(qū)分,false為不區(qū)分)wholeWord:是否僅匹配完整單詞(true時僅替換獨立的完整單詞)
以下示例演示將文檔中的舊公司名稱替換為新名稱:
public static void BasicReplace(string inputPath, string outputPath)
{
// 創(chuàng)建 Document 對象并加載文檔
Document document = new Document();
document.LoadFromFile(inputPath);
// 執(zhí)行替換操作:不區(qū)分大小寫,匹配完整單詞
document.Replace("old_company_name", "NewTech Solutions Inc.", false, true);
// 保存修改后的文檔
document.SaveToFile(outputPath, FileFormat.Docx);
document.Close();
}該方法在替換過程中能夠保留原文本的格式與排版,確保文檔的其他元素(如圖片、表格、頁眉頁腳等)不受影響。
可選:僅替換首次出現(xiàn)的文本
若業(yè)務(wù)需求僅需將文檔中第一次出現(xiàn)的目標(biāo)文本進(jìn)行替換,可在調(diào)用 Replace 方法之前將 Document.ReplaceFirst 屬性設(shè)置為 true:
public static void ReplaceFirstInstance(string inputPath, string outputPath)
{
Document document = new Document();
document.LoadFromFile(inputPath);
// 將替換模式設(shè)置為僅替換第一個匹配項
document.ReplaceFirst = true;
document.Replace("placeholder", "actual value", false, true);
document.SaveToFile(outputPath, FileFormat.Docx);
document.Close();
}進(jìn)階:使用正則表達(dá)式進(jìn)行模式匹配替換
對于需要匹配某種模式而非固定字符串的場景(例如替換所有占位符 {{...}}、匹配特定格式的編號等),可以使用 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(@"\{\{.*?\}\}");
// 將所有匹配的占位符替換為目標(biāo)字符串
document.Replace(placeholderRegex, "replacement text");
document.SaveToFile(outputPath, FileFormat.Docx);
document.Close();
}更復(fù)雜的使用場景中,還可調(diào)用 Replace(Regex, TextSelection) 等重載變體進(jìn)行帶格式的替換操作。
擴展:查找文本并做進(jìn)一步處理(查找高亮)
除了直接替換,Document.FindAllString 方法可以獲取所有匹配的 TextSelection 對象集合,便于在替換前對匹配結(jié)果進(jìn)行預(yù)覽、統(tǒng)計,或在替換后應(yīng)用格式設(shè)置(如高亮顯示)。
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)
{
// 將匹配的文本設(shè)置為高亮黃色
selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
}
document.SaveToFile(outputPath, FileFormat.Docx);
document.Close();
}知識擴展
在 .NET 項目中實現(xiàn) Word 文檔的自動化文本替換,不需要操作界面,有幾種成熟的方案。根據(jù)項目是內(nèi)部工具還是商業(yè)產(chǎn)品,以及預(yù)算和文檔規(guī)模,選擇會有所不同。
基礎(chǔ)替換:簡單字符串替換
最直接的需求是把文檔中的占位符(如 {{Name}})替換成具體值。
using Spire.Doc;
Document doc = new Document("Template.docx");
// 在整個文檔范圍內(nèi)替換
// 參數(shù):目標(biāo)文本、新文本、是否區(qū)分大小寫、是否僅匹配完整單詞
doc.Replace("{{PartyA}}", "張三", true, true);
doc.Replace("{{PartyB}}", "李四", true, true);
doc.SaveToFile("Output.docx", FileFormat.Docx);如果你的文檔中沒有使用特殊的占位符標(biāo)記(如 {{...}}),還可以結(jié)合正則表達(dá)式做更靈活的匹配:例如 new Regex(@"\{[^\}]+\}") 可以匹配所有被花括號包裹的文本。
正則匹配:批量匹配模式化占位符
對于模板中存在大量相似占位符的情況,正則表達(dá)式是更高效的選擇。
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 預(yù)先獲取所有匹配項,進(jìn)行預(yù)覽或統(tǒng)計:
csharp
TextSelection[] matches = doc.FindAllString(placeholderPattern, true);
Console.WriteLine($"找到 {matches.Length} 處占位符");分段處理:應(yīng)對大文檔的內(nèi)存優(yōu)化
如果文檔較大,可以采用分段處理的方式,避免一次性加載整個文檔。經(jīng)過分段處理后,100 頁合同的內(nèi)存峰值可從 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 釋放一次緩存,降低內(nèi)存峰值
if (section.Index % 5 == 0)
doc.ClearCache();
}
doc.SaveToFile("Output.docx", FileFormat.Docx);Interop方式:依賴Word環(huán)境
如果項目中必須使用 Interop,請務(wù)必做好資源釋放,否則容易導(dǎo)致 Word 進(jìn)程殘留。
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();
}批量處理多個文檔與動態(tài)填充
實際業(yè)務(wù)中,最典型的場景是:從數(shù)據(jù)庫或 Excel 中讀取多組數(shù)據(jù),分別填充到多個 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> 建立映射表,然后遍歷所有映射項統(tǒng)一替換,方便新增/修改占位符:
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);總結(jié)
本文提供了一套較為完整的 Word 文檔文本替換示例:從基礎(chǔ)的 Replace 字符串替換、僅替換首次出現(xiàn)、正則表達(dá)式模式匹配,到 FindAllString 查找并做格式調(diào)整,基本覆蓋了 .NET 環(huán)境下 Word 文檔批量處理的常見需求。
在實際項目中,建議根據(jù)文檔規(guī)模和業(yè)務(wù)復(fù)雜度選擇合適的替換策略;對于需要格式保留的復(fù)雜內(nèi)容場景,可進(jìn)一步利用其他重載或自行封裝處理。
到此這篇關(guān)于C#代碼實現(xiàn)Word文檔文本批量替換(動態(tài)填充)的文章就介紹到這了,更多相關(guān)C#批量替換Word文本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
通過LinQ查詢字符出現(xiàn)次數(shù)的實例方法
這篇文章主要介紹了通過LinQ查詢字符出現(xiàn)次數(shù)的實例方法,大家參考使用吧2013-11-11

