跳至頁尾內容
使用 IRONWORD

如何在 C# 中使用 Word 範本產生 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.檔案路徑:指定範本( Template.docx )和輸出檔案( 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 範本自動化有哪些好處?

使用 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 Framework。然後,透過 NuGet 套件管理器將 IronWord 加入您的專案中。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。