使用IRONWORD

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

雷根·彭
雷根·彭
2024年十月24日
分享:

在现代应用中,为账单、发票、信件等各种目的即时生成 Word 文档至关重要。Microsoft Word 模板文档功能为确保一致性和效率提供了一种强大的方法。 然而,手动填充这些模板既耗时又容易出错。 这就是IronWord的用武之地,它是由Iron Software开发的一款强大的.NET库,旨在通过编程自动化填充Word模板的过程。 在本文中,我们将介绍如何使用IronWord填充Word文档模板,并提供一个实用的示例来说明该过程。

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

  1. 在 Microsoft Visual Studio 中创建一个新项目。

  2. 通过 NuGet 包管理器安装IronWord

  3. 创建 Word 模板文档。

  4. 将数据插入 Word 文档并保存为新文件。

  5. 为生成的 Word 文档添加文本效果。

什么是IronWord?

IronWord 是来自 Iron 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 项目开始。

如何使用Word模板在C#中生成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 安装。

如何在 C# 中使用 Word 模板生成 Word 文档:图 6 - 复制命令并粘贴到 NuGet 控制台应用程序中

dotnet add package IronWord --version 2024.9.1
dotnet add package IronWord --version 2024.9.1
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronWord --version 2024.9.1
$vbLabelText   $csharpLabel

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

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

Dear {Name},
Thanks for Purchasing {product}, 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 expiry date.
Fell Free to contact {phone} or {email} for further queries.
Address: {Address}
Thank you,
{Sender}
Dear {Name},
Thanks for Purchasing {product}, 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 expiry date.
Fell Free to contact {phone} or {email} for further queries.
Address: {Address}
Thank you,
{Sender}
Dear
If True Then
	Name
End If
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
', Thanks for Purchasing
'{
'	product
'}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
', happy @to serve you always.Your application dated
'{
'	@Date
'}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'has been approved.The product comes @with an expiry @date @of
'{
'	expiryDate
'}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'.Renew the product on @or before expiry @date.Fell Free @to contact
'{
'	phone
'}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@or {email} for further queries.Address:
'{
'	Address
'}
Thank you,
If True Then
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'	Sender}
$vbLabelText   $csharpLabel

现在将上述文档保存为 Template.docx。

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

using IronWord;
class Program
{
    static void Main()
    {
        License.LicenseKey = "your key";
        // Define the path to the template and the output file object sender
        string templatePath = "Template.docx";
        string outputPath = "FilledDocument.docx";
        // Create a new instance of the WordDocument class
        WordDocument doc = new WordDocument(templatePath);
            // Define a dictionary/ first table 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 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);
        Console.WriteLine("Document filled and saved successfully.");
    }
}
using IronWord;
class Program
{
    static void Main()
    {
        License.LicenseKey = "your key";
        // Define the path to the template and the output file object sender
        string templatePath = "Template.docx";
        string outputPath = "FilledDocument.docx";
        // Create a new instance of the WordDocument class
        WordDocument doc = new WordDocument(templatePath);
            // Define a dictionary/ first table 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 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);
        Console.WriteLine("Document filled and saved successfully.");
    }
}
Imports IronWord
Friend Class Program
	Shared Sub Main()
		License.LicenseKey = "your key"
		' Define the path to the template and the output file object sender
		Dim templatePath As String = "Template.docx"
		Dim outputPath As String = "FilledDocument.docx"
		' Create a new instance of the WordDocument class
		Dim doc As New WordDocument(templatePath)
			' Define a dictionary/ first table 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 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)
		Console.WriteLine("Document filled and saved successfully.")
	End Sub
End Class
$vbLabelText   $csharpLabel

说明

所提供的代码演示了如何使用 IronWord 库将特定数据填充到 Word 文档模板中。 下面是一个简明的解释:

  1. 许可证设置:代码首先设置 IronWord 的许可证密钥以激活其功能。

  2. 文件路径:它指定了Word模板 (`Template.docx`) 和输出文件 (`FilledDocument.docx`) 的路径。创建文档实例:使用模板路径引用创建了一个 `WordDocument` 实例。

  3. 定义替换项:创建一个字典,其中键表示模板中的占位符,值表示要插入的数据。5. 替换占位符:它遍历字典,将文档中的每个占位符替换为相应的数据。

  4. 保存文档:最后,使用保存方法并传递参数将更新后的文档保存到指定的输出路径。7. 完成消息:打印一条消息以确认文档已成功填写并保存。

    输出

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

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

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

在下面的示例中,我们为 Word Iron Software 添加了文字效果。

using IronWord;
using IronWord.Models;
class Program
{
    static void Main()
    {
        License.LicenseKey = "your key";
        // Define the path to the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "FilledDocument.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 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);
        //Console.WriteLine("Document filled and saved successfully.");
        // Create and configure text style methods
        TextStyle textStyle = new TextStyle();
        textStyle.TextEffect = new TextEffect()
        {
            GlowEffect = new Glow()
            {
                GlowColor = IronWord.Models.Color.Aqua,
                GlowRadius = 10,
            },
        };
        // Add text with style or image
        doc.AddText(" IronSoftware").Style = textStyle;
        // Export new Word document
        doc.SaveAs("glowEffect.docx");
    }
}
using IronWord;
using IronWord.Models;
class Program
{
    static void Main()
    {
        License.LicenseKey = "your key";
        // Define the path to the template and the output file
        string templatePath = "Template.docx";
        string outputPath = "FilledDocument.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 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);
        //Console.WriteLine("Document filled and saved successfully.");
        // Create and configure text style methods
        TextStyle textStyle = new TextStyle();
        textStyle.TextEffect = new TextEffect()
        {
            GlowEffect = new Glow()
            {
                GlowColor = IronWord.Models.Color.Aqua,
                GlowRadius = 10,
            },
        };
        // Add text with style or image
        doc.AddText(" IronSoftware").Style = textStyle;
        // Export new Word document
        doc.SaveAs("glowEffect.docx");
    }
}
Imports IronWord
Imports IronWord.Models
Friend Class Program
	Shared Sub Main()
		License.LicenseKey = "your key"
		' Define the path to 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
		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 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);
		'Console.WriteLine("Document filled and saved successfully.");
		' Create and configure text style methods
		Dim textStyle As New TextStyle()
		textStyle.TextEffect = New TextEffect() With {
			.GlowEffect = New Glow() With {
				.GlowColor = IronWord.Models.Color.Aqua,
				.GlowRadius = 10
			}
		}
		' Add text with style or image
		doc.AddText(" IronSoftware").Style = textStyle
		' Export new Word document
		doc.SaveAs("glowEffect.docx")
	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. 控制台输出:之前的控制台输出语句已被注释掉,并且保存操作已更新以反映新文档名称。

    这段代码演示了 IronWord 的文档自动化和定制功能,包括文本替换和样式设计。

    输出

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

IronWord 许可

IronWord。 输入数据后,许可证将发送至所提供的电子邮件 ID。 此许可证需要在代码开头放置,在使用IronWord库之前,如下所示。

License.LicenseKey = "your Key Here"
License.LicenseKey = "your Key Here"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'License.LicenseKey = "your Key Here"
$vbLabelText   $csharpLabel

结论

IronWord 提供了通过模板生成 Word 文档的几个优势。 它允许开发人员以编程方式在模板中填写特定数据,减少了手动输入的需要,从而简化了文档创建自动化。 这样可以提高效率和准确性,因为人为错误的风险降到了最低。 此外,IronWord 有助于维护文档的一致性,确保每个生成的文件遵循相同的格式和结构。 自动化重复性任务可以节省时间和资源,是快速制作大量文件的理想选择。 IronWord 在需要频繁或复杂文档生成的场景中提高生产力并简化工作流程。

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

雷根·彭
软件工程师
Regan毕业于雷丁大学,拥有电子工程学士学位。在加入Iron Software之前,他的前工作职位要求他专注于单一任务;他在Iron Software最喜欢的是能进行多种工作,无论是增加销售价值、技术支持、产品开发还是营销。他喜欢了解开发人员如何使用Iron Software的库,并利用这些知识不断改进文档和开发产品。
< 前一页
如何使用 C# 在 Word 中对齐文本
下一步 >
如何用 C# 在 Word 文件中添加水印

准备开始了吗? 版本: 2025.4 刚刚发布

查看许可证 >