跳至页脚内容
使用 IRONWORD

如何使用 Word 模板在 C# 中生成 Word 文档

在现代应用中,即时生成 Word 文档以用于各种用途(例如账单、发票、信函等)至关重要。Microsoft Word 的模板文档功能提供了一种强大的方法来确保一致性和效率。 然而,手动填写这些模板既费时又容易出错。 这时, Iron SoftwareIronWord就派上了用场——这是一个强大的 .NET 库,旨在以编程方式自动填充 Word 模板。 在本文中,我们将逐步介绍如何使用IronWord填充 Word 文档模板,并提供一个实际示例来说明该过程。

如何在 C# 中使用 Word 模板生成 Word 文档

  1. 在 Microsoft Visual Studio 中创建一个新项目。
  2. 通过 NuGet 包管理器安装IronWord
  3. 创建 Word 模板文档。
  4. 将数据插入 Word 文档并另存为新文件。
  5. 为生成的 Word 文档添加文本效果。

IronWord是什么?

IronWordIron Software开发的一个 .NET 库,旨在以编程方式简化 Microsoft Word 文档的创建、操作和管理。 它允许开发人员自动生成 Word 文档,从而更容易在应用程序中动态创建报告、发票、信函和其他类型的文档。

IronWord 的主要特点

1. C# 填充 Word 模板和处理

IronWord允许使用 Word 模板在模板文档中定义占位符,并在运行时将其替换为实际数据。

2. 文本处理

您可以轻松地在 Word 文档中插入、替换或删除文本。

3. 格式设置

该库支持多种格式设置选项,包括字体样式、大小、颜色和段落对齐方式。

4. 表格和图片

IronWord允许您在文档中插入和操作表格和图像。

5. 兼容性

它可与不同版本的 Microsoft Word 无缝协作,确保兼容性和易用性。

用例

*报表生成*:利用动态数据自动生成详细报表。 创建发票:填写客户和交易详情,创建专业发票。 合同管理:自动创建包含个性化信息的合同。 信函和通知**:为客户或员工生成个性化的信函和通知。

IronWord 简化了在 .NET 应用程序中处理 Word 文档的操作,对于希望自动化文档生成和管理任务的开发人员来说,它是一款非常有价值的工具。

前提条件

开始之前,请您务必准备好以下物品:

  • 您的计算机上已安装 Visual Studio。
  • 已安装最新版本的 .NET Framework。

步骤 1:在 Microsoft Visual Studio 中创建一个新项目。

现在,让我们从创建一个新的 Visual Studio 项目开始。

如何在 C# 中使用 Word 模板生成 Word 文档:图 1

请在下方屏幕上选择控制台应用程序模板。

如何在 C# 中使用 Word 模板生成 Word 文档:图 2 - 选择控制台应用程序

提供项目名称和位置。

如何在 C# 中使用 Word 模板生成 Word 文档:图 3 - 提供名称和位置

选择 .NET 版本,最好选择有支持的最新版本,然后单击"创建"。

如何在 C# 中使用 Word 模板生成 Word 文档:图 4

步骤 2:安装 IronWord NuGet 包管理器。

在 Visual Studio 中,按照以下步骤从 NuGet 包管理器安装 IronWord NuGet 包。

如何在 C# 中使用 Word 模板生成 Word 文档:图 5 - 从 NuGet 包管理器中搜索 IronWord

或者,请使用以下命令直接通过 CLI 安装。

dotnet add package IronWord --version 2024.9.1
dotnet add package IronWord --version 2024.9.1
SHELL

步骤 3:创建 Word 模板文档。

现在,生成一个包含一到两页的 Word 模板文档,以便在 Word 文档生成过程中使用。

Dear {Name},

Thanks for purchasing {product}. We are happy to serve you always. Your application dated {Date} has been approved. The product comes with an expiry date of {expiryDate}. Renew the product on or before the expiry date.

Feel free to contact {phone} or {email} for further queries.

Address: {Address}

Thank you,

{Sender}

现在,将上述文档另存为Template.docx

步骤 4:将数据插入 Word 文档并另存为新文件。

using System;
using System.Collections.Generic;
using IronWord;

class Program
{
    static void Main()
    {
        // Set the license key for IronWord
        License.LicenseKey = "your key";

        // Define paths for the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "FilledDocument.docx";

        // Create a new instance of the WordDocument class using the template path
        WordDocument doc = new WordDocument(templatePath);

        // Define a dictionary of placeholders and their replacements
        var replacements = new Dictionary<string, string>
        {
            { "{Name}", "John Doe" },
            { "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
            { "{Address}", "123 Iron Street, Iron Software" },
            { "{product}", "IronWord" },
            { "{Sender}", "IronSoftware" },
            { "{phone}", "+123 456789" },
            { "{email}", "sale@ironsoftware.com" },
            { "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
        };

        // Replace placeholders in the document with actual data
        foreach (var replacement in replacements)
        {
            doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
        }

        // Save the filled document
        doc.Save(outputPath);

        // Notify the user that the document has been saved successfully
        Console.WriteLine("Document filled and saved successfully.");
    }
}
using System;
using System.Collections.Generic;
using IronWord;

class Program
{
    static void Main()
    {
        // Set the license key for IronWord
        License.LicenseKey = "your key";

        // Define paths for the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "FilledDocument.docx";

        // Create a new instance of the WordDocument class using the template path
        WordDocument doc = new WordDocument(templatePath);

        // Define a dictionary of placeholders and their replacements
        var replacements = new Dictionary<string, string>
        {
            { "{Name}", "John Doe" },
            { "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
            { "{Address}", "123 Iron Street, Iron Software" },
            { "{product}", "IronWord" },
            { "{Sender}", "IronSoftware" },
            { "{phone}", "+123 456789" },
            { "{email}", "sale@ironsoftware.com" },
            { "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
        };

        // Replace placeholders in the document with actual data
        foreach (var replacement in replacements)
        {
            doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
        }

        // Save the filled document
        doc.Save(outputPath);

        // Notify the user that the document has been saved successfully
        Console.WriteLine("Document filled and saved successfully.");
    }
}
Imports System
Imports System.Collections.Generic
Imports IronWord

Friend Class Program
	Shared Sub Main()
		' Set the license key for IronWord
		License.LicenseKey = "your key"

		' Define paths for the template and the output file
		Dim templatePath As String = "Template.docx"
		Dim outputPath As String = "FilledDocument.docx"

		' Create a new instance of the WordDocument class using the template path
		Dim doc As New WordDocument(templatePath)

		' Define a dictionary of placeholders and their replacements
		Dim replacements = New Dictionary(Of String, String) From {
			{"{Name}", "John Doe"},
			{"{Date}", DateTime.Now.ToString("MMMM d, yyyy")},
			{"{Address}", "123 Iron Street, Iron Software"},
			{"{product}", "IronWord"},
			{"{Sender}", "IronSoftware"},
			{"{phone}", "+123 456789"},
			{"{email}", "sale@ironsoftware.com"},
			{"{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy")}
		}

		' Replace placeholders in the document with actual data
		For Each replacement In replacements
			doc.Texts.ForEach(Function(x) x.Replace(replacement.Key, replacement.Value))
		Next replacement

		' Save the filled document
		doc.Save(outputPath)

		' Notify the user that the document has been saved successfully
		Console.WriteLine("Document filled and saved successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

解释

提供的代码演示了如何使用 IronWord 库将特定数据填充到 Word 文档模板中。 以下是简要说明: 1.许可证设置:代码首先设置 IronWord 的许可证密钥以激活其功能。 2.文件路径:它指定 Word 模板 ( Template.docx ) 和输出文件 ( FilledDocument.docx ) 的路径。 3.创建文档实例:使用模板路径引用创建WordDocument实例。 4.定义替换:创建一个字典,其中键表示模板中的占位符,值表示要插入的数据。 5.替换占位符:它遍历字典,将文档中的每个占位符替换为相应的数据。 6.保存文档:最后,将更新后的文档保存到指定的输出路径。 7.完成信息:打印一条信息以确认文档已成功填写并保存。

Output

如何在 C# 中使用 Word 模板生成 Word 文档:图 7 - Word 文档输出

步骤 5:为生成的 Word 文档添加文本效果。

IronWord 还允许添加各种文本效果,如下表所示。

在以下示例中,我们为单词"Iron Software"添加文本效果。

using System;
using System.Collections.Generic;
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Set the license key for IronWord
        License.LicenseKey = "your key";

        // Define paths for the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "glowEffect.docx";

        // Create a new instance of the WordDocument class
        WordDocument doc = new WordDocument(templatePath);

        // Define a dictionary of placeholders and their replacements
        var replacements = new Dictionary<string, string>
        {
            { "{Name}", "John Doe" },
            { "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
            { "{Address}", "123 Iron Street, Iron Software" },
            { "{product}", "IronWord" },
            { "{Sender}", "Sale," },
            { "{phone}", "+123 456789" },
            { "{email}", "sale@ironsoftware.com" },
            { "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
        };

        // Replace placeholders in the document with actual data
        foreach (var replacement in replacements)
        {
            doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
        }

        // Create and configure text style methods with a glow effect
        TextStyle textStyle = new TextStyle
        {
            TextEffect = new TextEffect()
            {
                GlowEffect = new Glow()
                {
                    GlowColor = IronWord.Models.Color.Aqua,
                    GlowRadius = 10,
                },
            }
        };

        // Add styled text to the document
        doc.AddText(" IronSoftware").Style = textStyle;

        // Save the document with the glow effect
        doc.SaveAs(outputPath);

        // Notify the user that the document has been saved successfully
        Console.WriteLine("Styled document saved successfully.");
    }
}
using System;
using System.Collections.Generic;
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Set the license key for IronWord
        License.LicenseKey = "your key";

        // Define paths for the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "glowEffect.docx";

        // Create a new instance of the WordDocument class
        WordDocument doc = new WordDocument(templatePath);

        // Define a dictionary of placeholders and their replacements
        var replacements = new Dictionary<string, string>
        {
            { "{Name}", "John Doe" },
            { "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
            { "{Address}", "123 Iron Street, Iron Software" },
            { "{product}", "IronWord" },
            { "{Sender}", "Sale," },
            { "{phone}", "+123 456789" },
            { "{email}", "sale@ironsoftware.com" },
            { "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
        };

        // Replace placeholders in the document with actual data
        foreach (var replacement in replacements)
        {
            doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
        }

        // Create and configure text style methods with a glow effect
        TextStyle textStyle = new TextStyle
        {
            TextEffect = new TextEffect()
            {
                GlowEffect = new Glow()
                {
                    GlowColor = IronWord.Models.Color.Aqua,
                    GlowRadius = 10,
                },
            }
        };

        // Add styled text to the document
        doc.AddText(" IronSoftware").Style = textStyle;

        // Save the document with the glow effect
        doc.SaveAs(outputPath);

        // Notify the user that the document has been saved successfully
        Console.WriteLine("Styled document saved successfully.");
    }
}
Imports System
Imports System.Collections.Generic
Imports IronWord
Imports IronWord.Models

Friend Class Program
	Shared Sub Main()
		' Set the license key for IronWord
		License.LicenseKey = "your key"

		' Define paths for the template and the output file
		Dim templatePath As String = "Template.docx"
		Dim outputPath As String = "glowEffect.docx"

		' Create a new instance of the WordDocument class
		Dim doc As New WordDocument(templatePath)

		' Define a dictionary of placeholders and their replacements
		Dim replacements = New Dictionary(Of String, String) From {
			{"{Name}", "John Doe"},
			{"{Date}", DateTime.Now.ToString("MMMM d, yyyy")},
			{"{Address}", "123 Iron Street, Iron Software"},
			{"{product}", "IronWord"},
			{"{Sender}", "Sale,"},
			{"{phone}", "+123 456789"},
			{"{email}", "sale@ironsoftware.com"},
			{"{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy")}
		}

		' Replace placeholders in the document with actual data
		For Each replacement In replacements
			doc.Texts.ForEach(Function(x) x.Replace(replacement.Key, replacement.Value))
		Next replacement

		' Create and configure text style methods with a glow effect
		Dim textStyle As New TextStyle With {
			.TextEffect = New TextEffect() With {
				.GlowEffect = New Glow() With {
					.GlowColor = IronWord.Models.Color.Aqua,
					.GlowRadius = 10
				}
			}
		}

		' Add styled text to the document
		doc.AddText(" IronSoftware").Style = textStyle

		' Save the document with the glow effect
		doc.SaveAs(outputPath)

		' Notify the user that the document has been saved successfully
		Console.WriteLine("Styled document saved successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

解释

修改后的代码演示了如何使用 IronWord 库来填写 Word 文档模板、设置文本样式并保存修改后的文档。 以下是简要说明:

1.许可证设置:设置 IronWord 许可证密钥以启用功能。 2.文件路径:指定模板( Template.docx )和输出文件( glowEffect.docx )的路径。 3.创建文档实例:使用提供的模板路径初始化WordDocument实例。 4.定义替换项:创建一个占位符及其对应替换值的字典。 5.替换占位符:遍历字典,将文档中的占位符替换为实际数据。 6.配置文本样式:定义带有发光效果的文本样式,指定颜色和半径。 7.添加样式文本:向文档中添加具有已配置样式的文本。 8.保存文档:将更新后的文档保存为新名称( glowEffect.docx ),以反映应用的文本样式。 9.控制台输出:打印一条消息以确认样式文档已保存。

Output

如何在 C# 中使用 Word 模板生成 Word 文档:图 8 - Word 输出示例

IronWord 授权

IronWord. 数据录入完毕后,许可证将发送到所提供的电子邮件地址。 在使用IronWord库之前,需要将此许可放在代码的开头,如下所示。

License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here"
$vbLabelText   $csharpLabel

结论

IronWord在使用模板生成 Word 文档方面具有诸多优势。 它简化了文档创建自动化流程,允许开发人员以编程方式使用特定数据填充模板,从而减少了手动输入的需要。 这样可以提高效率和准确性,因为人为错误的风险降到了最低。 此外, IronWord还有助于保持文档之间的一致性,确保生成的每个文件都遵循相同的格式和结构。 自动化重复性任务可以节省时间和资源,因此非常适合快速生成大量文档。 IronWord可提高工作效率,并简化需要频繁或复杂文档生成的场景下的工作流程。

通过按照本文概述的步骤并利用提供的IronWord示例,您可以有效地管理文档生成需求并简化工作流程。

常见问题解答

如何使用 C# 填充 Word 文档模板?

您可以通过利用 IronWord 使用 C# 填充 Word 文档模板。首先,在 Visual Studio 中设置项目,并通过 NuGet 安装 IronWord 包。创建一个 Word 模板,使用 IronWord 插入数据,然后将填充后的模板另存为新文档。

使用 .NET 库进行 Word 模板自动化有什么好处?

使用像 IronWord 这样的 .NET 库进行 Word 模板自动化可减少手动输入,最小化错误,并确保文档创建的一致性。它可以有效地处理计费、开票和书信编写等任务。

在程序中填充 Word 模板时可以添加文字效果吗?

是的,使用 IronWord,您可以在程序化填充模板时为 Word 文档中的文本添加发光或阴影等文字效果。

在 Visual Studio 项目中设置 IronWord 需要哪些步骤?

要在 Visual Studio 项目中设置 IronWord,首先安装 IronWord NuGet 包,创建您的 Word 模板,然后使用 IronWord 的方法来程序化填充和保存文档。

IronWord 如何确保文档生成的一致性?

IronWord 通过允许开发人员使用保持相同格式和布局的 Word 模板来确保多个文档之间的一致性,从而减少人为错误的风险。

自动化 Word 文档生成的实际应用有哪些?

使用 IronWord 自动化 Word 文档生成可以应用于各种场景,包括报告生成、发票创建、合同管理和个性化信件撰写。

使用 IronWord 可以处理不同版本的 Microsoft Word 吗?

是的,IronWord 兼容多个版本的 Microsoft Word,可以在不同环境中无缝处理文档。

开始使用 IronWord 进行 Word 文档管理需要什么?

要开始使用 IronWord,确保您已安装 Visual Studio,并具有最新的 .NET 框架。然后,通过 NuGet 包管理器将 IronWord 添加到项目中。

Jordi Bardia
软件工程师
Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。