使用 IRONWORD 如何使用 Word 模板在 C# 中生成 Word 文档 Jordi Bardia 已更新:六月 22, 2025 Download IronWord NuGet 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article In modern-day applications, it is crucial to generate Word documents on the fly for various purposes like billing, invoices, letters, etc. The Microsoft Word template document feature offers a powerful way to ensure consistency and efficiency. However, manually populating these templates can be time-consuming and prone to errors. That’s where IronWord from Iron Software comes in—a robust .NET library designed to automate the process of filling Word templates programmatically. In this article, we’ll walk through how to use IronWord to fill a Word document template and provide a practical example to illustrate the process. How to Generate a Word Document Using a Word Template in C# Create a new project in Microsoft Visual Studio. Install IronWord through NuGet package manager. Create a Word Template document. Insert data into a Word document and save it as a new file. Add text effects to the generated Word document. What is IronWord? IronWord is a .NET library from Iron Software designed to facilitate the creation, manipulation, and management of Microsoft Word documents programmatically. It allows developers to automate the process of generating Word documents, making it easier to dynamically create reports, invoices, letters, and other types of documents within their applications. Key Features of IronWord 1. C# Fill Word Template and Handling IronWord enables the use of Word templates to define placeholders in a template document and replace them with actual data at runtime. 2. Text Manipulation You can easily insert, replace, or delete text within a Word document. 3. Formatting The library supports various formatting options, including font styles, sizes, colors, and paragraph alignment. 4. Tables and Images IronWord allows you to insert and manipulate tables and images within your documents. 5. Compatibility It works seamlessly with different versions of Microsoft Word, ensuring compatibility and ease of use. Use Cases Report Generation: Automatically generate detailed reports with dynamic data. Invoice Creation: Create professional invoices by filling in customer and transaction details. Contract Management: Automate the creation of contracts with personalized information. Letters and Notices: Generate personalized letters and notices for clients or employees. IronWord simplifies working with Word documents in .NET applications, making it a valuable tool for developers who want to automate document generation and management tasks. Prerequisites A quick reminder to make sure you have the following before we get started: Visual Studio is installed on your machine. The latest .NET Framework is installed. Step 1: Create a new project in Microsoft Visual Studio. Now, let us begin by creating a new Visual Studio project. Select the console application template on the screen below. Provide the project name and location. Select the .NET Version, preferably the latest one with support, and click Create. Step 2: Install IronWord NuGet Package manager. Install IronWord NuGet package from NuGet package manager as below in Visual Studio. Alternatively, please install it using CLI directly using the command below. dotnet add package IronWord --version 2024.9.1 dotnet add package IronWord --version 2024.9.1 SHELL Step 3: Create a Word Template document. Now, generate a Word template document with one or two pages to be used during the Word document generation process. 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} Now, save the document above as Template.docx. Step 4: Inserting data into a Word document and saving as a new file. 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 Explanation The provided code demonstrates using the IronWord library to fill a Word document template with specific data. Here’s a concise explanation: License Setup: The code begins by setting the license key for IronWord to activate its functionality. File Paths: It specifies the paths for the Word template (Template.docx) and the output file (FilledDocument.docx). Create Document Instance: An instance of WordDocument is created using the template path reference. Define Replacements: A dictionary is created where keys represent placeholders in the template, and values represent the data to insert. Replace Placeholders: It iterates through the dictionary, replacing each placeholder in the document with the corresponding data. Save Document: Finally, the updated document is saved to the specified output path. Completion Message: A message is printed to confirm that the document has been successfully filled and saved. Output Step 5: Add text effects to generated Word document. IronWord also allows adding various text effects, as shown in the table below. In the following example, we add text effects to the word "IronSoftware". 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 Explanation The revised code illustrates using the IronWord library to fill out a Word document template, style text, and save the modified document. Here's a concise explanation: License Setup: Sets the IronWord license key to enable functionality. File Paths: Specifies the paths for the template (Template.docx) and the output file (glowEffect.docx). Create Document Instance: Initializes a WordDocument instance using the provided template path. Define Replacements: Creates a dictionary of placeholders and their corresponding replacement values. Replace Placeholders: Iterates through the dictionary, replacing placeholders in the document with actual data. Configure Text Style: Defines a text style with a glow effect, specifying color and radius. Add Styled Text: Adds text with the configured style to the document. Save Document: Saves the updated document with a new name (glowEffect.docx), reflecting the applied text style. Console Output: A message is printed to confirm that the styled document has been saved. Output IronWord Licensing IronWord. Once the data is entered, the license is delivered to the email ID provided. This license needs to be placed at the beginning of the code, before using the IronWord library, as below. License.LicenseKey = "your Key Here"; License.LicenseKey = "your Key Here"; License.LicenseKey = "your Key Here" $vbLabelText $csharpLabel Conclusion IronWord offers several advantages for generating Word documents using templates. It simplifies document creation automation by allowing developers to programmatically fill out templates with specific data, reducing the need for manual input. This increases efficiency and accuracy, as the risk of human error is minimized. Additionally, IronWord helps maintain consistency across documents, ensuring that each generated file adheres to the same format and structure. Automating repetitive tasks saves time and resources, making it ideal for quickly producing large volumes of documents. IronWord enhances productivity and streamlines workflows in scenarios requiring frequent or complex document generation. By following the steps outlined in this article and leveraging the provided example with IronWord, you can efficiently manage your document generation needs and streamline your workflow. 常见问题解答 如何使用 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 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。 相关文章 已更新九月 18, 2025 ASP .NET Core 导入和导出 Word 文件 本指南探讨了如何使用 IronWord 库导入现有的 Word 文档、显示其内容并从头创建文档 阅读更多 已更新七月 28, 2025 VS 2022 编程创建新 Word 文档 (教程) 在今天的教程中,我将简要解释如何使用 IronWord 编程创建 Microsoft Word 文档并提供简短示例。 阅读更多 已更新六月 22, 2025 如何使用 C# 在 Word 中对齐文本 深入了解 IronWord NuGet 包以及使用该包对齐文本或段落的方法 阅读更多 如何使用 C# 在 Word 中对齐文本如何在 C# 中向 Word 文件添...
已更新七月 28, 2025 VS 2022 编程创建新 Word 文档 (教程) 在今天的教程中,我将简要解释如何使用 IronWord 编程创建 Microsoft Word 文档并提供简短示例。 阅读更多