跳過到頁腳內容
使用 IRONWORD

如何在 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.");
    }
}
$vbLabelText   $csharpLabel

解釋

提供的程式碼示範如何使用IronWord庫將特定資料填入 Word 文件範本中。 以下是簡要說明: 1.許可證設定:代碼首先設定IronWord的許可證密鑰以啟動其功能。 2.檔案路徑:它指定 Word 範本 (Template.docx) 和輸出檔案 (FilledDocument.docx) 的路徑。 3.建立文件實例:使用範本路徑引用建立 WordDocument 的實例。 4.定義替換:建立字典,其中鍵表示模板中的佔位符,值表示要插入的資料。 5.替換佔位符:它遍歷字典,將文件中的每個佔位符替換為對應的資料。 6.儲存文件:最後,將更新後的文件儲存到指定的輸出路徑。 7.完成資訊:列印一則資訊以確認文件已成功填寫並儲存。

輸出

如何在 C# 中使用 Word 範本產生 Word 文件:圖 7 - Word 文件輸出

步驟 5:為產生的 Word 文件新增文字效果

IronWord也允許添加各種文字效果,如下表所示。

在以下範例中,我們為單字"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.");
    }
}
$vbLabelText   $csharpLabel

解釋

修改後的程式碼示範如何使用IronWord庫來填寫 Word 文件範本、設定文字樣式並儲存修改後的文件。 以下是簡要說明:

1.許可證設定:設定IronWord許可證密鑰以啟用功能。 2.檔案路徑:指定範本(glowEffect.docx)的路徑。 3.建立文件實例:使用提供的範本路徑初始化 WordDocument 實例。 4.定義替換:建立佔位符及其對應替換值的字典。 5.取代佔位符:遍歷字典,將文件中的佔位符替換為實際資料。 6.配置文字樣式:定義帶有發光效果的文字樣式,指定顏色和半徑。 7.新增樣式文字:向文件中新增具有已配置樣式的文字。 8.儲存文件:將更新後的文件儲存為新名稱(glowEffect.docx),以反映套用的文字樣式。 9.控制台輸出:列印一則訊息以確認樣式文件已儲存。

輸出

如何在 C# 中使用 Word 範本產生 Word 文件:圖 8 - Word 輸出範例

IronWord授權

IronWord 。 資料錄入完畢後,許可證將發送到所提供的電子郵件地址。 在使用IronWord函式庫之前,需要將此授權放在程式碼的開頭,如下所示。

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 範本自動化有何好處?

使用 .NET 庫如 IronWord 進行 Word 範本自動化可以減少手動輸入,減少錯誤,並確保文檔創建的一致性。它允許高效處理諸如計費、開票和信件撰寫的任務。

在程式化填寫 Word 範本時可以添加文字效果嗎?

是的,使用 IronWord,您可以在程式化填寫範本時在 Word 文檔中的文本中添加光暈或陰影等文字效果。

設置 IronWord 在 Visual Studio 項目中涉及哪些步驟?

要在 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 Framework。然後,通過 NuGet 套件管理器將 IronWord 添加到您的項目中。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担產品测测试,產品開發和研究的责任時,Jordi 為持续的產品改進增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我