跳過到頁腳內容
使用 IRONWORD

VS 2022 程式化建立新 Word 文件 (教學)

在數位時代,文件正日益數位化。 在商業環境中,文件通常與微軟 Word 及其文件型 Word 文件相關聯。撰寫和編輯微軟 Word文件已成為大型組織中訊息傳遞的基礎。 然而,手動建立和編輯文件可能是一個痛苦的過程; 以程式設計方式自動產生 Word 文件也不是一件容易的事,因為許多開源程式庫都依賴 Microsoft Office Word。

然而,管理和建立 Word 文件並不一定非得這麼難。 IronWord是一個 C# Word 函式庫,它不依賴 Microsoft Office Word,允許使用者自訂整個文檔,同時也允許以程式設計方式產生文件和建立文件範本。

在今天的教程中,我將簡單解釋如何使用 IronWord 程式化創建 Microsoft Word 文檔,並提供簡單範例。

IronWord:AC# 字庫

IronWord 是一款極其可靠且使用者友好的 C# Docx 程式庫,它使開發人員能夠使用 C# 建立和修改 Word 文檔,而無需依賴 Microsoft Office 或 Word Interop 等傳統程式庫。此外,它擁有豐富的文檔,並全面支援 .NET 8、7、6、.NET Framework、.NET Core 和 Azure,使其與大多數應用程式具有廣泛的兼容性。 這種靈活性使其成為您可能遇到的任何應用的絕佳選擇。

建立環境

在這個範例中,我們將使用Visual Studio建立一個控制台應用程序,並展示如何建立空白 Word 文件以及如何使用 IronWord 程式庫對其進行操作。 在進行下一步之前,請確保您已安裝 Visual Studio。

首先,我們建立一個新的控制台應用程式。

然後,提供項目名稱並儲存位置,如下所示。

最後,選擇所需的框架。

安裝 C# Word 庫

建立空白控制台應用程式後,我們將透過 NuGet 套件管理器下載IronWord

點擊"管理 NuGet 套件",然後在"瀏覽"標籤中搜尋 IronWord,如下所示。

之後,將其安裝到新建立的專案中。

或者,您也可以在命令列中輸入以下命令來安裝 IronWord。

Install-Package IronWord

現在一切都已準備就緒,讓我們來看一個建立 Word 文件的範例。

許可證密鑰

請注意,IronWord 需要許可證密鑰才能運作。 您可以點擊此連結以取得免費試用金鑰。

// Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY";
// Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY";
' Replace the license key variable with the trial key you obtained
IronWord.License.LicenseKey = "REPLACE-WITH-YOUR-KEY"
$vbLabelText   $csharpLabel

收到試用金鑰後,請在項目中設定此變數。

建立新的 Word 文檔

using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Create a textrun
        Text textRun = new Text("Sample text");
        Paragraph paragraph = new Paragraph();
        paragraph.AddChild(textRun);

        // Create a new Word document with the paragraph
        WordDocument doc = new WordDocument(paragraph);

        // Export docx
        doc.SaveAs("document.docx");
    }
}
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Create a textrun
        Text textRun = new Text("Sample text");
        Paragraph paragraph = new Paragraph();
        paragraph.AddChild(textRun);

        // Create a new Word document with the paragraph
        WordDocument doc = new WordDocument(paragraph);

        // Export docx
        doc.SaveAs("document.docx");
    }
}
Imports IronWord
Imports IronWord.Models

Friend Class Program
	Shared Sub Main()
		' Create a textrun
		Dim textRun As New Text("Sample text")
		Dim paragraph As New Paragraph()
		paragraph.AddChild(textRun)

		' Create a new Word document with the paragraph
		Dim doc As New WordDocument(paragraph)

		' Export docx
		doc.SaveAs("document.docx")
	End Sub
End Class
$vbLabelText   $csharpLabel

! VS 2022 以程式設計方式建立新 Word 文件(教學):圖 6 - 上述範例的輸出

說明

  1. 首先,我們在範例程式碼中導入 IronWord 函式庫及其模型。
  2. 我們建立一個新的Text變數。 此變數允許我們在 Word 文件中新增文字。
  3. 然後我們將textRun加入到Paragraph 。 這樣我們就可以透過區分兩者來輕鬆處理文字。
  4. 我們將paragraph參數傳遞給一個新的WordDocument類,以建立一個新的文檔物件。
  5. 最後,我們將文件儲存為 Word 文件"document.docx"。

在前面的範例中,我們建立了一個包含基本文字的 Word 文件。 讓我們來看一個使用更高級功能的例子,例如自訂文字和添加文字效果。

using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Ensure to set up the license key
        IronWord.License.LicenseKey = "YOUR-KEY";

        // Load an existing docx
        WordDocument doc = new WordDocument("document.docx");

        // Create sample texts with styles
        Text introText = new Text("This is an example paragraph with italic and bold styling.");
        TextStyle italicStyle = new TextStyle()
        {
            IsItalic = true
        };
        Text italicText = new Text("Italic example sentence.");
        italicText.Style = italicStyle;

        TextStyle boldStyle = new TextStyle()
        {
            IsBold = true
        };
        Text boldText = new Text("Bold example sentence.");
        boldText.Style = boldStyle;

        // Create a paragraph and add texts
        Paragraph paragraph = new Paragraph();
        paragraph.AddText(introText);
        paragraph.AddText(italicText);
        paragraph.AddText(boldText);

        // Add paragraph to the document
        doc.AddParagraph(paragraph);

        // Export the document
        doc.SaveAs("save_document.docx");
    }
}
using IronWord;
using IronWord.Models;

class Program
{
    static void Main()
    {
        // Ensure to set up the license key
        IronWord.License.LicenseKey = "YOUR-KEY";

        // Load an existing docx
        WordDocument doc = new WordDocument("document.docx");

        // Create sample texts with styles
        Text introText = new Text("This is an example paragraph with italic and bold styling.");
        TextStyle italicStyle = new TextStyle()
        {
            IsItalic = true
        };
        Text italicText = new Text("Italic example sentence.");
        italicText.Style = italicStyle;

        TextStyle boldStyle = new TextStyle()
        {
            IsBold = true
        };
        Text boldText = new Text("Bold example sentence.");
        boldText.Style = boldStyle;

        // Create a paragraph and add texts
        Paragraph paragraph = new Paragraph();
        paragraph.AddText(introText);
        paragraph.AddText(italicText);
        paragraph.AddText(boldText);

        // Add paragraph to the document
        doc.AddParagraph(paragraph);

        // Export the document
        doc.SaveAs("save_document.docx");
    }
}
Imports IronWord
Imports IronWord.Models

Friend Class Program
	Shared Sub Main()
		' Ensure to set up the license key
		IronWord.License.LicenseKey = "YOUR-KEY"

		' Load an existing docx
		Dim doc As New WordDocument("document.docx")

		' Create sample texts with styles
		Dim introText As New Text("This is an example paragraph with italic and bold styling.")
		Dim italicStyle As New TextStyle() With {.IsItalic = True}
		Dim italicText As New Text("Italic example sentence.")
		italicText.Style = italicStyle

		Dim boldStyle As New TextStyle() With {.IsBold = True}
		Dim boldText As New Text("Bold example sentence.")
		boldText.Style = boldStyle

		' Create a paragraph and add texts
		Dim paragraph As New Paragraph()
		paragraph.AddText(introText)
		paragraph.AddText(italicText)
		paragraph.AddText(boldText)

		' Add paragraph to the document
		doc.AddParagraph(paragraph)

		' Export the document
		doc.SaveAs("save_document.docx")
	End Sub
End Class
$vbLabelText   $csharpLabel

! VS 2022 以程式設計方式建立新 Word 文件(教學):圖 7 - 上述範例程式碼的輸出

程式碼解釋

  1. 與上面的範例一樣,我們建立Text物件並新增文件的範例文字。
  2. 接著我們建立一個新的TextStyle對象,並將IsItalic屬性設為true ,表示文字應為斜體。
  3. 我們對boldText變數執行相同的操作,將IsBold屬性賦值為true
  4. 然後我們將TextStyle變數分配給它們各自的Text變數。
  5. 我們建立一個Paragraph變量,並呼叫AddText方法來加入斜體和粗體文字。
  6. 我們使用AddParagraph方法將段落加入到文件中。
  7. 最後,我們將文件儲存為"save_document.docx"。

以上範例展示了開發人員可以使用 IronWord 的字體和樣式。 除了斜體和粗體文字效果外,IronWord 還提供其他功能,確保開發人員在各種情況下都能建立獨特的 Word 文件。

結論

! VS 2022 以程式設計方式建立新 Word 文件(教學):圖 8 - IronWord 授權資訊

我們的示範表明,使用IronWord庫以 C# 程式設計方式建立 Word 文件是多麼容易。 該程式庫的靈活性和可擴展性使其成為開發人員在實際場景中(例如在 Word 文件中自訂文字、字體和樣式)的寶貴工具。 了解 Word 如何與其他應用程式集成,可以為開發人員提供更多應對挑戰的解決方案。

IronWord 提供免費試用授權

常見問題解答

如何使用 C# 程式化建立 Microsoft Word 文件?

您可以使用 IronWord 函式庫,以 C# 程式化的方式建立 Microsoft Word 文件。初始化 WordDocument 物件,新增必要的內容,並使用 SaveAs 方法將其匯出為 .docx 檔案。

與 Microsoft Office Interop 相比,使用 IronWord 創建 Word 文檔有哪些優點?

與 Microsoft Office Interop 相比,IronWord 的優勢在於無需安裝 Microsoft Office,提供了更大的靈活性和更容易的跨平台整合,而無需依賴 Office。

如何在 Visual Studio 中安裝 IronWord?

若要在 Visual Studio 中安裝 IronWord,請開啟 NuGet Package Manager,搜尋 IronWord,並將其安裝到您的專案中。或者,使用命令列 Install-Package IronWord

我可以使用 IronWord 格式化 Word 文件中的文字嗎?

是的,您可以使用 IronWord 格式化 Word 文件中的文字,方法是利用 TextStyle 物件將斜體和粗體等各種樣式套用至文字元素。

IronWord 是否與 .NET 和 Azure 相容?

是的,IronWord 與 .NET 8、7、6、Framework、Core 和 Azure 完全相容,使其成為各種應用程式的多面手。

如何排除 IronWord 的安裝問題?

如果您遇到 IronWord 的安裝問題,請確保您使用的是相容的 Visual Studio 和 .NET 版本,且您的 NuGet Package Manager 已更新。檢查您的網際網路連線,並重試安裝。

開始使用 IronWord 製作 Word 文件需要哪些條件?

若要開始使用 IronWord 建立 Word 文件,請將 IronWord 函式庫及其模型匯入您的 C# 專案。然後,初始化一個 WordDocument 物件,開始建立您的文件。

如何使用 IronWord 程式化地在 Word 文件中加入段落?

您可以使用 IronWord 程式化地在 Word 文件中加入段落,方法是建立 Paragraph 物件,將文字加入其中,並將其包含在 WordDocument 中。

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