C#代碼實(shí)現(xiàn)根據(jù)模板快速生成Word文檔
在日常開發(fā)中,我們經(jīng)常遇到需要批量生成合同、通知書、報(bào)告等Word文檔的場景。最優(yōu)雅的方式莫過于準(zhǔn)備一個(gè)模板文件,然后通過代碼替換其中的占位符,快速生成最終文檔。今天就來分享如何使用 Free Spire.Doc for .NET 輕松實(shí)現(xiàn)這一功能。
為什么選擇 Free Spire.Doc?
Free Spire.Doc 是一款免費(fèi)、易用的 Word 操作組件,無需安裝 Microsoft Office 即可完成文檔的創(chuàng)建、讀取、編輯和保存。它支持 .NET Framework 和 .NET Core,非常適合服務(wù)端批量處理場景。
通過 NuGet 安裝:
PM> Install-Package FreeSpire.Doc
實(shí)現(xiàn)思路
預(yù)先設(shè)計(jì)一個(gè) Word 模板(如 template.docx),用特定占位符標(biāo)記需要填充的內(nèi)容
在代碼中加載模板,將占位符替換為實(shí)際數(shù)據(jù)
支持文本替換,也支持插入圖片(如證件照)
保存為新的 Word 文檔
完整代碼
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace CreateWordByReplacingPlaceholders
{
class Program
{
static void Main(string[] args)
{
// Initialize a new Document object
Document document = new Document();
// Load the template Word file
document.LoadFromFile("C:\Users\Administrator\Desktop\template.docx");
// Dictionary to hold placeholders and their replacements
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "#name#", "李四" },
{ "#gender#", "男" },
{ "#birthdate#", "1990年3月20日" },
{ "#address#", "西安北路街道" },
{ "#city#", "成都" },
{ "#province#", "四川" },
{ "#postal#", "610000" },
{ "#country#", "中國" }
};
// Replace placeholders in the document with corresponding values
foreach (KeyValuePair<string, string> kvp in replaceDict)
{
document.Replace(kvp.Key, kvp.Value, true, true);
}
// Path to the image file
String imagePath = "C:\Users\Administrator\Desktop\portrait.png";
// Replace the placeholder for the photograph with an image
ReplaceTextWithImage(document, "#photo#", imagePath);
// Save the modified document
document.SaveToFile("ReplacePlaceholders.docx", FileFormat.Docx);
// Release resources
document.Dispose();
}
// Method to replace a placeholder in the document with an image
static void ReplaceTextWithImage(Document document, String stringToReplace, String imagePath)
{
// Load the image from the specified path
Image image = Image.FromFile(imagePath);
DocPicture pic = new DocPicture(document);
pic.LoadImage(image);
pic.Width = 130;
// Find the placeholder in the document
TextSelection selection = document.FindString(stringToReplace, false, true);
// Get the range of the found text
TextRange range = selection.GetAsOneRange();
int index = range.OwnerParagraph.ChildObjects.IndexOf(range);
// Insert the image and remove the placeholder text
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);
}
}
}

代碼詳解
1. 文本替換
首先準(zhǔn)備一個(gè)字典,存儲占位符與替換文本的對應(yīng)關(guān)系:
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "#name#", "李四" },
{ "#gender#", "男" },
// ... 其他字段
};
然后遍歷字典,調(diào)用 document.Replace 方法完成替換。該方法的后兩個(gè)參數(shù)分別表示是否區(qū)分大小寫和是否僅替換整個(gè)單詞。
2. 圖片替換
圖片替換稍微復(fù)雜一些,核心步驟如下:
- 使用
Image.FromFile加載圖片文件 - 創(chuàng)建
DocPicture對象并加載圖片,設(shè)置圖片寬度 - 通過
FindString定位占位符的位置 - 獲取占位符所在段落及索引
- 在相同位置插入圖片,然后移除占位符文本
3. 保存文檔
最后調(diào)用 SaveToFile 方法保存為新文檔,并釋放資源。
模板準(zhǔn)備建議
在 Word 模板中,將需要?jiǎng)討B(tài)填充的位置用占位符標(biāo)記,例如:
| 字段 | 占位符 |
|---|---|
| 姓名 | #name# |
| 性別 | #gender# |
| 出生日期 | #birthdate# |
| 照片 | #photo# |
使用注意事項(xiàng)
- 確保模板文件路徑和圖片路徑正確
- 占位符建議使用獨(dú)特標(biāo)識(如
#字段名#),避免誤替換 - 圖片替換時(shí)可調(diào)整
Width和Height屬性控制顯示尺寸 - 處理完成后記得調(diào)用
Dispose()釋放資源
總結(jié)
通過 Free Spire.Doc,我們只需維護(hù)一套模板文件,即可快速生成成千上萬份個(gè)性化文檔,大幅提升工作效率。該組件還支持合并單元格、設(shè)置字體樣式、添加頁眉頁腳等高級功能
到此這篇關(guān)于C#代碼實(shí)現(xiàn)根據(jù)模板快速生成Word文檔的文章就介紹到這了,更多相關(guān)C#模板生成Word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用C#實(shí)現(xiàn)阿拉伯?dāng)?shù)字到大寫中文的轉(zhuǎn)換
這篇文章主要介紹了C#實(shí)現(xiàn)阿拉伯?dāng)?shù)字轉(zhuǎn)為大寫中文的實(shí)現(xiàn)代碼,需要的朋友可以參考下2007-03-03
C#輕松實(shí)現(xiàn)文件讀取進(jìn)度監(jiān)控功能
使用C#進(jìn)行開發(fā)的工程師,掌握如何實(shí)現(xiàn)文件讀取進(jìn)度監(jiān)控是一項(xiàng)非常實(shí)用且有成就感的技能,下面我們就來看看如何開發(fā)一個(gè)支持文件讀取進(jìn)度監(jiān)控的功能吧2026-02-02
C#動(dòng)態(tài)生成實(shí)體類的5種方法詳解與實(shí)戰(zhàn)演示
這篇文章主要為大家詳細(xì)介紹了C#中動(dòng)態(tài)生成實(shí)體類的5種實(shí)用方法,涵蓋T4模板,CodeDOM,Roslyn,反射和Emit等技術(shù),有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04
解析C#編程的通用結(jié)構(gòu)和程序書寫格式規(guī)范
這篇文章主要介紹了C#編程的通用結(jié)構(gòu)和程序書寫格式規(guī)范,這里我們根據(jù)C#語言的開發(fā)方微軟給出的約定來作為編寫樣式參照,需要的朋友可以參考下2016-01-01
C#創(chuàng)建安全的字典(Dictionary)存儲結(jié)構(gòu)
本文主要對存儲結(jié)構(gòu)字典(Dictionary)的一些常用方法進(jìn)行簡單的說明,并闡述了如何創(chuàng)建安全的字典(Dictionary)存儲結(jié)構(gòu)。希望對大家有所幫助2016-12-12

