跳至頁尾內容
USING IRONWORD

如何在C#中使用IronWord向Word文件新增浮水印

在現代應用程式中,即時生成Word文件對於各種目的(如帳單、發票、信函等)是至關重要的。Microsoft Word範本文件功能提供了一種強大的方式來確保一致性和效率。 然而,手動填寫這些範本可能會耗時且容易出錯。 這就是來自Iron Software的IronWord的用武之地——這是一個強大的.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專案。

How to Generate a Word Document Using a Word Template in C#: Figure 1

在下方螢幕上選擇控制台應用程式範本。

How to Generate a Word Document Using a Word Template in C#: Figure 2 - Select Console App

提供專案名稱和位置。

How to Generate a Word Document Using a Word Template in C#: Figure 3 - Provide name and location

選擇.NET版本,最好是帶有支持的最新版本,然後點擊建立。

How to Generate a Word Document Using a Word Template in C#: Figure 4

步驟2:安裝IronWord NuGet套件管理器

在Visual Studio中,從NuGet套件管理器中安裝IronWord NuGet套件,如下所示。

How to Generate a Word Document Using a Word Template in C#: Figure 5 - Search for IronWord from NuGet Package Manager

或者,請直接使用以下指令在CLI中安裝它。

dotnet add package IronWord --version 2024.9.1

步驟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.");
    }
}
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

說明

提供的程式碼展示了如何使用IronWord程式庫將特定資料填入Word文件範本。 以下是簡要說明:

  1. 授權設定:程式碼首先設置IronWord的授權金鑰以啟用其功能。
  2. 文件路徑:指定Word範本(FilledDocument.docx)的路徑。
  3. 建立文件實例:使用範本路徑參照建立WordDocument實例。
  4. 定義替換:建立一個字典,其中鍵代表範本中的佔位符,值代表要插入的資料。
  5. 替換佔位符:遍歷字典,用相應的資料替換文件中的每個佔位符。
  6. 保存文件:最後,將更新的文件保存到指定的輸出路徑。
  7. 完成訊息:列印訊息以確認文件已成功填寫並保存。

輸出

How to Generate a Word Document Using a Word Template in C#: Figure 7 - Word Document Output

步驟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.");
    }
}
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

說明

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

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

輸出

How to Generate a Word Document Using a Word Template in C#: Figure 8 - Example Word Output

IronWord 授權

IronWord. 一旦輸入資料後,授權將發送到所提供的電子郵件ID。 此授權需要放在程式碼的開頭,在使用IronWord程式庫之前,如下所示。

License.LicenseKey = "your Key Here";
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文件的文字中。

設置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加入到您的項目中。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

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