C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#模板生成Word

C#代码实现根据模板快速生成Word文档

作者:LSTM97

在日常开发中,我们经常遇到需要批量生成合同、通知书、报告等Word文档的场景,今天小编就来分享如何使用 Free Spire.Doc for .NET 轻松实现根据模板快速生成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

实现思路

预先设计一个 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. 图片替换

图片替换稍微复杂一些,核心步骤如下:

3. 保存文档

最后调用 SaveToFile 方法保存为新文档,并释放资源。

模板准备建议

在 Word 模板中,将需要动态填充的位置用占位符标记,例如:

字段占位符
姓名#name#
性别#gender#
出生日期#birthdate#
照片#photo#

使用注意事项

总结

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

到此这篇关于C#代码实现根据模板快速生成Word文档的文章就介绍到这了,更多相关C#模板生成Word内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文