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

相关推荐
rit84324992 小时前
基于NSGA-II的多目标优化算法(MATLAB实现)
开发语言·算法·matlab
小碗羊肉2 小时前
【从零开始学Java | 第三十篇】不可变集合
java·开发语言
专注VB编程开发20年2 小时前
Delphi 的VCL控件库无法公开给其他编程语言调用
开发语言·delphi
charlie1145141912 小时前
现代Qt开发——0.1——如何在IDE中配置Qt环境?
开发语言·c++·ide·qt·嵌入式
游乐码2 小时前
c#StringBuilder
开发语言·c#
五阿哥永琪2 小时前
record只读类
java·开发语言
枫叶丹42 小时前
【HarmonyOS 6.0】窗口能力增强:PC/2in1与自由多窗模式的深度解析
开发语言·华为·harmonyos
AI科技星2 小时前
基于三维空间合速度恒为光速公理的统一动力学与热力学理论:温度本质的第一性原理诠释与物质全物态实验验证
开发语言·线性代数·机器学习·计算机视觉·数学建模
Dovis(誓平步青云)2 小时前
《QT学习第二篇:QT的常用控件属性与按钮、view系列、Label、输入框》
开发语言·qt·学习