C#:通过模板快速生成 Word 文档

在日常开发中,我们经常遇到需要批量生成合同、通知书、报告等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

实现思路

  1. 预先设计一个 Word 模板(如 template.docx),用特定占位符标记需要填充的内容
  2. 在代码中加载模板,将占位符替换为实际数据
  3. 支持文本替换,也支持插入图片(如证件照)
  4. 保存为新的 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#

使用注意事项

  1. 确保模板文件路径和图片路径正确
  2. 占位符建议使用独特标识(如 #字段名#),避免误替换
  3. 图片替换时可调整 WidthHeight 属性控制显示尺寸
  4. 处理完成后记得调用 Dispose() 释放资源

总结

通过 Free Spire.Doc,我们只需维护一套模板文件,即可快速生成成千上万份个性化文档,大幅提升工作效率。该组件还支持合并单元格、设置字体样式、添加页眉页脚等高级功能,感兴趣的朋友可以深入探索!

相关推荐
Gofarlic_oms16 小时前
利用API实现ANSYS许可证管理自动化集成
运维·服务器·开发语言·matlab·自动化·负载均衡
AI+程序员在路上7 小时前
VS Code 完全使用指南:下载、安装、核心功能与 内置AI 编程助手实战
开发语言·人工智能·windows·开源
invicinble8 小时前
这里对java的知识体系做一个全域的介绍
java·开发语言·python
catchadmin8 小时前
使用 PHP TrueAsync 改造 Laravel 协程异步化的可行路径
开发语言·php·laravel
wbs_scy8 小时前
【Linux 线程进阶】进程 vs 线程资源划分 + 线程控制全详解
java·开发语言
AI人工智能+电脑小能手8 小时前
【大白话说Java面试题】【Java基础篇】第15题:JDK1.7中HashMap扩容为什么会发生死循环?如何解决
java·开发语言·数据结构·后端·面试·哈希算法
郑州光合科技余经理9 小时前
同城O2O海外版二次开发实战:从支付网关到配送算法
开发语言·前端·后端·算法·架构·uni-app·php
南子北游10 小时前
Python学习(基础语法1)
开发语言·python·学习
张健115640964810 小时前
使用信号量限制并发数量
开发语言·c++
糯米团子74910 小时前
Web Worker
开发语言·前端·javascript