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

相关推荐
优橙教育31 分钟前
5G网优培训 vs Java开发:转行选哪个?
java·开发语言·5g
SeaTunnel2 小时前
从 Python Script 地狱到标准化数据集成框架
大数据·开发语言·python·程序员·代码·seatunnel
碎光拾影3 小时前
ARM交叉工具链各工具作用及IMX6ULL平台LED+蜂鸣器裸机程序实现
java·开发语言·数据库
Marst Code3 小时前
(python)2026Plotly 库评估:交互式可视化到底值不值得引入?
开发语言·python
Miao121314 小时前
微服务 API 测试实践:海外某民宿平台如何构建模式驱动测试基础设施
java·开发语言
CRMEB系统商城5 小时前
开源自建还是SaaS订阅?算一笔3年经济账
java·大数据·开发语言·开源
keyipatience6 小时前
线程栈与TLS和线程互斥
java·linux·服务器·开发语言·ubuntu
我的xiaodoujiao6 小时前
快速学习Python基础知识详细图文教程9--函数进阶
开发语言·python·学习·测试工具
爱喝水的鱼丶6 小时前
SAP-ABAP:ALV通用封装实践——搭建可复用的ALV开发工具类,减少80%重复代码
开发语言·性能优化·sap·abap·erp·alv
脱胎换骨-军哥7 小时前
C++/Rust无缝互操作:混合系统新常态
开发语言·c++·rust