C# 通过模板生成 Word 文档:文本与图片占位符替换完整攻略

发布时间:2026/7/9 6:26:26
C# 通过模板生成 Word 文档:文本与图片占位符替换完整攻略 在办公自动化开发中根据固定模板批量生成 Word 文档如合同、报告、简历、通知书等是最常见的需求之一。本文将介绍如何使用Spire.Doc for .NET组件通过加载模板文件将文档中的文本占位符替换为真实数据并支持将占位符替换为图片最终生成一份完整的 Word 文档。为什么选择 Spire.DocSpire.Doc 是一款功能强大的 .NET Word 组件无需安装 Microsoft Office 即可创建、读取、编辑和转换 Word 文档。它提供了丰富的 API尤其Document.Replace()方法可以快速完成文本替换而结合FindString()与DocPicture又能灵活实现图片插入非常适合模板填充场景。代码实现步骤下面通过一个完整的控制台程序示例演示如何将模板中的#name#、#gender#等占位符替换为实际内容并将#photo#替换为一张图片。1. 引入命名空间与初始化文档using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing;创建Document对象并加载模板文件.docxDocument document new Document(); document.LoadFromFile(Template.docx);2. 文本占位符替换建立一个字典键为占位符如#name#值为真实数据。这里我们将示例内容本地化为中文环境Dictionarystring, string replaceDict new Dictionarystring, string { { #name#, 张三 }, { #gender#, 男 }, { #birthdate#, 1990年1月15日 }, { #address#, 上海市浦东新区 }, { #city#, 上海 }, { #state#, 直辖市 }, { #postal#, 200120 }, { #country#, 中国 } };遍历字典调用document.Replace(占位符, 替换值, true, true)完成全文档替换。后两个布尔参数分别表示是否区分大小写和是否匹配整个单词这里按需设置。3. 图片占位符替换文本替换无法处理图片因此我们需要单独实现一个方法ReplaceTextWithImage。其核心逻辑是用Image.FromFile()加载图片创建DocPicture对象并载入图片通过document.FindString()定位占位符#photo#所在的TextRange获取该TextRange在段落子对象中的索引将图片插入同一位置然后删除占位符文本。static void ReplaceTextWithImage(Document document, string stringToReplace, string imagePath) { Image image Image.FromFile(imagePath); DocPicture pic new DocPicture(document); pic.LoadImage(image); TextSelection selection document.FindString(stringToReplace, false, true); TextRange range selection.GetAsOneRange(); int index range.OwnerParagraph.ChildObjects.IndexOf(range); range.OwnerParagraph.ChildObjects.Insert(index, pic); range.OwnerParagraph.ChildObjects.Remove(range); }调用时传入图片路径ReplaceTextWithImage(document, #photo#, portrait.png);4. 保存与释放最后将文档保存为新文件并释放资源document.SaveToFile(ReplacePlaceholders.docx, FileFormat.Docx); document.Dispose();完整代码一览using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace CreateWordByReplacingTextPlaceholders { class Program { static void Main(string[] args) { Document document new Document(); document.LoadFromFile(Template.docx); Dictionarystring, string replaceDict new Dictionarystring, string { { #name#, 张三 }, { #gender#, 男 }, { #birthdate#, 1990年1月15日 }, { #address#, 上海市浦东新区 }, { #city#, 上海 }, { #state#, 直辖市 }, { #postal#, 200120 }, { #country#, 中国 } }; foreach (var kvp in replaceDict) { document.Replace(kvp.Key, kvp.Value, true, true); } ReplaceTextWithImage(document, #photo#, portrait.png); document.SaveToFile(ReplacePlaceholders.docx, FileFormat.Docx); document.Dispose(); } static void ReplaceTextWithImage(Document document, string stringToReplace, string imagePath) { Image image Image.FromFile(imagePath); DocPicture pic new DocPicture(document); pic.LoadImage(image); TextSelection selection document.FindString(stringToReplace, false, true); TextRange range selection.GetAsOneRange(); int index range.OwnerParagraph.ChildObjects.IndexOf(range); range.OwnerParagraph.ChildObjects.Insert(index, pic); range.OwnerParagraph.ChildObjects.Remove(range); } } }注意事项与扩展模板设计在 Word 模板中占位符必须与代码中的字符串完全一致包括大小写和特殊符号建议使用明显的标记如#或{{}}以避免误替换。图片处理ReplaceTextWithImage方法假设占位符独立存在于一个段落中若占位符与其他文本同行插入图片后可能会影响排版可根据业务调整插入位置。性能优化对于大量文档生成可复用Document对象或使用内存流操作。字体与样式替换文本后新内容会继承原占位符的样式如需自定义样式可操作TextRange的CharacterFormat属性。总结通过 Spire.Doc 提供的简洁 API我们仅用几十行代码就实现了 Word 模板的数据填充既支持文本又支持图片。这种方式极大地提高了文档生成的效率和准确性非常适合企业级报表、证书打印、批量信函等场景。开发者只需关注模板设计和数据来源剩下的交给代码即可。如果你正在寻找轻量级、无 Office 依赖的 Word 操作方案Spire.Doc 无疑是一个值得尝试的选择。希望本文能帮助你快速上手为你的项目增添自动化生成文档的能力。