如何使用IronWord在 C# 中为 Word 文档添加水印
在现代应用中,即时生成 Word 文档以用于各种用途(例如账单、发票、信函等)至关重要。Microsoft Word 的模板文档功能提供了一种强大的方法来确保一致性和效率。 然而,手动填写这些模板既费时又容易出错。 这时, Iron Software的IronWord就派上了用场——这是一个强大的 .NET 库,旨在以编程方式自动填充 Word 模板。 在本文中,我们将逐步介绍如何使用IronWord填充 Word 文档模板,并提供一个实际示例来说明该过程。
如何在 C# 中使用 Word 模板生成 Word 文档
- 在 Microsoft Visual Studio 中创建一个新项目。
- 通过 NuGet 包管理器安装IronWord 。
- 创建 Word 模板文档。
- 将数据插入 Word 文档并另存为新文件。
- 为生成的 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 项目开始。

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

提供项目名称和位置。

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

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

或者,请使用以下命令直接通过 CLI 安装。
步骤 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.");
}
}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解释
提供的代码演示了如何使用 IronWord 库将特定数据填充到 Word 文档模板中。 以下是简要说明:
- **许可证设置:**代码首先设置 IronWord 的许可证密钥以激活其功能。
- **文件路径:**指定Word模板的路径(
FilledDocument.docx)。 - **创建文档实例:**使用模板路径引用创建一个
WordDocument实例。 - **定义替换项:**创建一个字典,其中键代表模板中的占位符,值代表待插入的数据。
- **替换占位符:**它遍历字典,将文档中的每个占位符替换为对应的数据。
- **保存文档:**最后,将更新后的文档保存到指定的输出路径。
- **完成提示:**系统将显示一条消息,确认文档已成功填写并保存。
输出

步骤 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.");
}
}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解释
修改后的代码演示了如何使用 IronWord 库来填写 Word 文档模板、设置文本样式并保存修改后的文档。 以下是简要说明:
- **许可证设置:**设置 IronWord 许可证密钥以启用相关功能。
- **文件路径:**指定模板(
glowEffect.docx)的路径。 - **创建文档实例:**使用提供的模板路径初始化一个
WordDocument实例。 - **定义替换项:**创建一个包含占位符及其对应替换值的字典。
- **替换占位符:**遍历字典,将文档中的占位符替换为实际数据。
- **配置文本样式:**定义一种带有发光效果的文本样式,并指定颜色和半径。
- **添加样式化文本:**将具有配置样式文本添加到文档中。
- **保存文档:**以新名称(
glowEffect.docx)保存更新后的文档,反映所应用的文本样式。 - **控制台输出:**系统会显示一条消息,以确认格式化后的文档已保存。
输出

IronWord 授权
IronWord 。 数据录入完毕后,许可证将发送到所提供的电子邮件地址。 在使用IronWord库之前,需要将此许可放在代码的开头,如下所示。
License.LicenseKey = "your Key Here";License.LicenseKey = "your Key Here"结论
IronWord在使用模板生成 Word 文档方面具有诸多优势。 它简化了文档创建自动化流程,允许开发人员以编程方式使用特定数据填充模板,从而减少了手动输入的需要。 这样可以提高效率和准确性,因为人为错误的风险降到了最低。 此外, IronWord还有助于保持文档之间的一致性,确保生成的每个文件都遵循相同的格式和结构。 自动化重复性任务可以节省时间和资源,因此非常适合快速生成大量文档。 IronWord可提高工作效率,并简化需要频繁或复杂文档生成的场景下的工作流程。
通过按照本文概述的步骤并利用提供的IronWord示例,您可以有效地管理文档生成需求并简化工作流程。

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。
相关文章

