在日常开发中,我们经常遇到需要批量生成合同、通知书、报告等Word文档的场景。最优雅的方式莫过于准备一个模板文件,然后通过代码替换其中的占位符,快速生成最终文档。今天就来分享如何使用 Free Spire.Doc for .NET 轻松实现这一功能。
为什么选择 Free Spire.Doc?
Free Spire.Doc 是一款免费、易用的 Word 操作组件,无需安装 Microsoft Office 即可完成文档的创建、读取、编辑和保存。它支持 .NET Framework 和 .NET Core,非常适合服务端批量处理场景。
通过 NuGet 安装:
PM> Install-Package FreeSpire.Doc
实现思路
- 预先设计一个 Word 模板(如
template.docx),用特定占位符标记需要填充的内容 - 在代码中加载模板,将占位符替换为实际数据
- 支持文本替换,也支持插入图片(如证件照)
- 保存为新的 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. 文本替换
首先准备一个字典,存储占位符与替换文本的对应关系:
Dictionary<string, string> replaceDict = new Dictionary<string, string>
{
{ "#name#", "李四" },
{ "#gender#", "男" },
// ... 其他字段
};
然后遍历字典,调用 document.Replace 方法完成替换。该方法的后两个参数分别表示是否区分大小写和是否仅替换整个单词。
2. 图片替换
图片替换稍微复杂一些,核心步骤如下:
- 使用
Image.FromFile加载图片文件 - 创建
DocPicture对象并加载图片,设置图片宽度 - 通过
FindString定位占位符的位置 - 获取占位符所在段落及索引
- 在相同位置插入图片,然后移除占位符文本
3. 保存文档
最后调用 SaveToFile 方法保存为新文档,并释放资源。
模板准备建议
在 Word 模板中,将需要动态填充的位置用占位符标记,例如:
| 字段 | 占位符 |
|---|---|
| 姓名 | #name# |
| 性别 | #gender# |
| 出生日期 | #birthdate# |
| 照片 | #photo# |
使用注意事项
- 确保模板文件路径和图片路径正确
- 占位符建议使用独特标识(如
#字段名#),避免误替换 - 图片替换时可调整
Width和Height属性控制显示尺寸 - 处理完成后记得调用
Dispose()释放资源
总结
通过 Free Spire.Doc,我们只需维护一套模板文件,即可快速生成成千上万份个性化文档,大幅提升工作效率。该组件还支持合并单元格、设置字体样式、添加页眉页脚等高级功能,感兴趣的朋友可以深入探索!
