跳過到頁腳內容
使用 IRONWORD

如何在 C# 中建立沒有 Office Interop 的 Word 文件

Microsoft Word 文件用途廣泛,從正式的商業報告到私人信件均可使用。 在 C# 中,開發人員經常需要以程式設計方式產生 Microsoft Word 文件。 Windows 應用程式開發人員歷來使用 Microsoft Office Interop 和 C# 產生和建立 Word 文件。

然而,這種方法並非人人都能接受,有些開發者使用的作業系統或 Linux 機器上可能沒有 Microsoft Office 介面。 在這種情況下,開發人員必須探索其他可以在不同平台上獨立運作的程式庫。 IronWordIron Software出品的一個功能強大的庫,可用於以程式設計方式處理 Word 文件。

IronWord 為在 .NET 應用程式中處理 Word 文件提供了強大的功能,並且可以在不同的平台和基於 Linux 的 docker 映像/容器上運行。 IronWord 具有直覺的 C#、VB.NET Word 和 Docx 文件 API,無需安裝 Microsoft Office、Office 自動化或 Word Interop 即可建置、編輯和匯出 Word 文件檔案。 IronWord 完全支援 .NET 8、7、6、Framework、Core 和 Azure。

本文將探討如何使用 IronWord 函式庫在 C# 中建立 Word 文件。

如何在不使用 Office Interop 的情況下用 C# 建立 Word 文檔

1.建立一個新的 C# 專案。

  1. 安裝IronWord庫。
  2. 使用 IronWord 庫建立 Word 文件。
  3. 在現有文件中新增內容。
  4. 儲存已建立的 Word 文件。
  5. 開啟並顯示已建立的 Word 文件。

先決條件:

1.Visual Studio: 確保您已安裝 Visual Studio 或任何其他 C# 開發環境。 2.NuGet套件管理員:確保您可以使用NuGet管理專案中的套件。

步驟 1:建立一個新的 C# 項目

建立一個新的 C# 控制台應用程序,或使用一個現有的專案來產生 Word 文件。

選擇控制台應用程式模板,然後按一下下一步。

如何在不使用 Office Interop 的情況下用 C# 建立 Word 文件:圖 1 - 用於建立新專案的控制台應用程式模板

下一步,您可以提供解決方案名稱和專案名稱。

如何在不使用 Office Interop 的情況下用 C# 建立 Word 文件:圖 2 - 使用解決方案和專案名稱設定項目

選擇 .NET 版本,然後按一下"建立"。

如何在不使用 Office Interop 的情況下用 C# 建立 Word 文件:圖 3 - 使用正確的 .NET 版本建立項目

步驟 2:安裝 IronWord 函式庫

開啟您的 C# 項目,並使用 NuGet 套件管理器控制台安裝IronWord庫:

Install-Package IronWord -Version 2024.1.2

也可以使用 Visual Studio 套件管理器安裝 NuGet 套件,如下圖所示。

如何在不使用 Office Interop 的情況下用 C# 建立 Word 文件:圖 4 - 使用 VS 套件管理器安裝 IronWord

步驟 3:使用 IronWord 庫建立並儲存 Word 文件

讓我們從使用 IronWord 庫建立 Word 文件這個簡單的範例開始。 以下程式碼示範如何建立一個包含單一段落的 Word 文檔,該段落的內容為"Hello, World!"

using IronWord;
using IronWord.Models;

// Create a text run instance with "Hello, World!" content
TextRun textRun = new TextRun("Hello, World!");

// Create a paragraph and add the text run to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

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

// Save the document as a .docx file
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
using IronWord;
using IronWord.Models;

// Create a text run instance with "Hello, World!" content
TextRun textRun = new TextRun("Hello, World!");

// Create a paragraph and add the text run to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

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

// Save the document as a .docx file
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
Imports IronWord
Imports IronWord.Models

' Create a text run instance with "Hello, World!" content
Private textRun As New TextRun("Hello, World!")

' Create a paragraph and add the text run to it
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)

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

' Save the document as a .docx file
doc.SaveAs("example.docx") ' Saves the file to disk with the name example.docx
$vbLabelText   $csharpLabel

執行上述程式碼範例後,將建立新文件文件example.docx ,輸出結果如下所示。

如何在 C# 中不使用 Office Interop 建立 Word 文件:圖 5 - 透過上述程式碼建立的 Word 文件。

這是一個使用 IronWord 產生 Word 文件檔案的基本範例。 如需了解更多信息,您可以閱讀文件

在 Word 文件中新增帶有樣式的段落

現在我們已經知道如何使用 IronWord 建立簡單的 Word 文檔,接下來讓我們新增段落和樣式文字。

TextRun 還可以獲得樣式數據,增強文字的視覺效果。 文字可以設定刪除線、粗體、斜體和底線等樣式。

修改以下程式碼並將其新增至您先前編寫的程式。

using IronWord;
using IronWord.Models;

// Create text runs with different styles
TextRun textRun = new TextRun("Hello, World!"); // Simple string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Configure and add italic text
TextRun introText = new TextRun("This is an example paragraph with italic and bold styling.");
TextStyle italicStyle = new TextStyle()
{
    IsItalic = true
};
TextRun italicText = new TextRun("Italic example sentence.", italicStyle);

// Configure and add bold text
TextStyle boldStyle = new TextStyle()
{
    IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);

// Add text runs to the paragraph
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);

// Create and save the new Word document
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
using IronWord;
using IronWord.Models;

// Create text runs with different styles
TextRun textRun = new TextRun("Hello, World!"); // Simple string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Configure and add italic text
TextRun introText = new TextRun("This is an example paragraph with italic and bold styling.");
TextStyle italicStyle = new TextStyle()
{
    IsItalic = true
};
TextRun italicText = new TextRun("Italic example sentence.", italicStyle);

// Configure and add bold text
TextStyle boldStyle = new TextStyle()
{
    IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);

// Add text runs to the paragraph
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);

// Create and save the new Word document
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("example.docx"); // Saves the file to disk with the name example.docx
Imports IronWord
Imports IronWord.Models

' Create text runs with different styles
Private textRun As New TextRun("Hello, World!") ' Simple string
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)

' Configure and add italic text
Dim introText As New TextRun("This is an example paragraph with italic and bold styling.")
Dim italicStyle As New TextStyle() With {.IsItalic = True}
Dim italicText As New TextRun("Italic example sentence.", italicStyle)

' Configure and add bold text
Dim boldStyle As New TextStyle() With {.IsBold = True}
Dim boldText As New TextRun("Bold example sentence.", boldStyle)

' Add text runs to the paragraph
paragraph.AddTextRun(introText)
paragraph.AddTextRun(italicText)
paragraph.AddTextRun(boldText)

' Create and save the new Word document
Dim doc As New WordDocument(paragraph)
doc.SaveAs("example.docx") ' Saves the file to disk with the name example.docx
$vbLabelText   $csharpLabel

在 Word 文件中新增表格

為了更清晰地呈現數據,也可以用網格的形式來表示。 當資料以網格形式排列時,就稱為表格。 使用 IronWord,我們可以在 Word 文件中新增表格和圖片,如下所示:

using IronWord;
using IronWord.Models;

// Create a table cell with sample text
TableCell cell = new TableCell();
TextRun textRun = new TextRun("Sample text");

// Add text run to the cell as a paragraph
cell.AddContent(new Paragraph(textRun));

// Configure cell border style
BorderStyle borderStyle = new BorderStyle
{
    BorderColor = new IronColor(IronSoftware.Drawing.Color.Black),
    BorderValue = IronWord.Models.Enums.BorderValues.Thick,
    BorderSize = 5
};

// Set table borders
TableBorders tableBorders = new TableBorders
{
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle
};
cell.Borders = tableBorders;

// Create a table row and add cells to it
TableRow row = new TableRow();
row.AddCell(cell); // Add the first cell
row.AddCell(cell); // Add the second cell, duplicating to mimic a row with two identical cells

// Create a table and add the row to the table
Table table = new Table();
table.AddRow(row);

// Create and save a Word document using the table
WordDocument doc = new WordDocument(table);
doc.SaveAs("Document.docx"); // Saves the file to disk with the name Document.docx
using IronWord;
using IronWord.Models;

// Create a table cell with sample text
TableCell cell = new TableCell();
TextRun textRun = new TextRun("Sample text");

// Add text run to the cell as a paragraph
cell.AddContent(new Paragraph(textRun));

// Configure cell border style
BorderStyle borderStyle = new BorderStyle
{
    BorderColor = new IronColor(IronSoftware.Drawing.Color.Black),
    BorderValue = IronWord.Models.Enums.BorderValues.Thick,
    BorderSize = 5
};

// Set table borders
TableBorders tableBorders = new TableBorders
{
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle
};
cell.Borders = tableBorders;

// Create a table row and add cells to it
TableRow row = new TableRow();
row.AddCell(cell); // Add the first cell
row.AddCell(cell); // Add the second cell, duplicating to mimic a row with two identical cells

// Create a table and add the row to the table
Table table = new Table();
table.AddRow(row);

// Create and save a Word document using the table
WordDocument doc = new WordDocument(table);
doc.SaveAs("Document.docx"); // Saves the file to disk with the name Document.docx
Imports IronWord
Imports IronWord.Models

' Create a table cell with sample text
Private cell As New TableCell()
Private textRun As New TextRun("Sample text")

' Add text run to the cell as a paragraph
cell.AddContent(New Paragraph(textRun))

' Configure cell border style
Dim borderStyle As New BorderStyle With {
	.BorderColor = New IronColor(IronSoftware.Drawing.Color.Black),
	.BorderValue = IronWord.Models.Enums.BorderValues.Thick,
	.BorderSize = 5
}

' Set table borders
Dim tableBorders As New TableBorders With {
	.TopBorder = borderStyle,
	.RightBorder = borderStyle,
	.BottomBorder = borderStyle,
	.LeftBorder = borderStyle
}
cell.Borders = tableBorders

' Create a table row and add cells to it
Dim row As New TableRow()
row.AddCell(cell) ' Add the first cell
row.AddCell(cell) ' Add the second cell, duplicating to mimic a row with two identical cells

' Create a table and add the row to the table
Dim table As New Table()
table.AddRow(row)

' Create and save a Word document using the table
Dim doc As New WordDocument(table)
doc.SaveAs("Document.docx") ' Saves the file to disk with the name Document.docx
$vbLabelText   $csharpLabel

在上面的範例中,我們使用邊框向 Word 文件中新增了一個表格。

在 Word 文件中新增圖片

圖片可以增強文件的呈現效果,並增添更多色彩和視覺吸引力。

可以使用 IronWord 以程式設計方式將圖片新增至 Word 文件中,如下面的程式碼所示:

using IronWord;
using IronWord.Models;

// Load a new document
WordDocument doc = new WordDocument();

// Configure and add image to the document
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg")
{
    Width = 200, // Set image width in pixels
    Height = 200 // Set image height in pixels
};
Paragraph paragraph = new Paragraph();
paragraph.AddImage(image); // Add image to paragraph
doc.AddParagraph(paragraph); // Add paragraph to the document

// Save the document as a .docx file
doc.SaveAs("save_document.docx"); // Saves the file to disk with the name save_document.docx
using IronWord;
using IronWord.Models;

// Load a new document
WordDocument doc = new WordDocument();

// Configure and add image to the document
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg")
{
    Width = 200, // Set image width in pixels
    Height = 200 // Set image height in pixels
};
Paragraph paragraph = new Paragraph();
paragraph.AddImage(image); // Add image to paragraph
doc.AddParagraph(paragraph); // Add paragraph to the document

// Save the document as a .docx file
doc.SaveAs("save_document.docx"); // Saves the file to disk with the name save_document.docx
Imports IronWord
Imports IronWord.Models

' Load a new document
Private doc As New WordDocument()

' Configure and add image to the document
Private image As New IronWord.Models.Image("SalesChart.jpg") With {
	.Width = 200,
	.Height = 200
}
Private paragraph As New Paragraph()
paragraph.AddImage(image) ' Add image to paragraph
doc.AddParagraph(paragraph) ' Add paragraph to the document

' Save the document as a .docx file
doc.SaveAs("save_document.docx") ' Saves the file to disk with the name save_document.docx
$vbLabelText   $csharpLabel

這裡,我們使用IronWord.Models.Image來為段落中新增一個高度和寬度均為 200 像素的圖像。

授權(可免費試用)

使用IronWord需要授權。 從Iron Software網站取得試用金鑰。此金鑰需要加入到appsettings.json中。

{
    "IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}

提供您的電子郵件以取得試用授權。 提交您的電子郵件地址後,金鑰將透過電子郵件發送給您。

如何在不使用 Office Interop 的情況下用 C# 建立 Word 文件:圖 6 - 試用表單成功提交後的彈出窗口

結論

使用IronWord庫在 C# 中建立 Word 文檔,無需依賴 Microsoft Office,即可靈活且有效率地產生文檔。無論您需要建立簡單的信函,還是包含表格和圖像的複雜報告,IronWord 都能以程式設計方式幫助您輕鬆實現。 本文提供了創建 Word 文件的全面教學。 透過 IronWord,您可以自動建立 Word 文檔,使您的 C# 應用程式更加靈活高效。

對於希望將 PDF 文件操作與生成的 Word 文件結合使用的開發人員來說, IronPDF是 Iron Software 開發的另一個 C# 庫,無需再尋找其他工具。

常見問題解答

如何在不使用 Microsoft Office Interop 的情況下以 C# 建立 Word 文件?

您可以利用 IronWORD 函式庫,在不使用 Microsoft Office Interop 的情況下以 C# 建立 Word 文件。這個函式庫可讓您以程式化的方式產生、編輯和儲存 Word 文件,而無需安裝 Microsoft Office。

與 Microsoft Office Interop 相比,使用 IronWord 有哪些優勢?

IronWord 提供了在非 Windows 平台(如 Linux)上運行的彈性,在這些平台上 Microsoft Office Interop 並不可用。它也消除了安裝 Microsoft Office 的依賴性,簡化了開發流程。

如何開始使用 IronWORD 創建 Word 文檔?

要開始使用 IronWORD 建立 Word 文件,首先要在您的 C# 專案中透過 NuGet 套件管理員安裝 IronWORD 函式庫。然後,使用 IronWORD API 程式化地建立和操作 Word 文件。

我可以在最新的 .NET 版本中使用 IronWord 嗎?

是的,IronWord 與各種 .NET 版本相容,包括 .NET 8、7、6、Framework、Core 和 Azure,讓您可以將其整合到現代 C# 應用程式中。

如何使用 IronWORD 在 Word 文檔中加入樣式化文字?

IronWORD 允許您使用 TextRunTextStyle 類別新增樣式化文字。這些類別可讓您在 Word 文件中的特定文字區段套用粗體、斜體和底線等樣式。

是否可以使用 IronWORD 在 Word 文件中包含表格?

是的,您可以使用 IronWORD 在 Word 文件中包含表格。該函式庫可讓您定義具有行和單元格的表格,並可使用邊框和其他樣式自訂其外觀。

如何使用 IronWORD 在 Word 文檔中插入圖片?

要使用 IronWord 在 Word 文檔中插入圖片,您可以使用 IronWord.Models.Image 類將指定尺寸的圖片嵌入到段落中,增強文檔的視覺內容。

IronWord 是否有試用版可供評估?

是的,Iron Software 提供 IronWORD 免費試用版,您可以從他們的網站下載。該試用版允許您在購買之前評估該函式庫的特性和功能。

Iron Software 還提供哪些其他的文件處理程式庫?

除了 IronWORD 之外,Iron Software 還提供 IronPDF 這個用於處理 PDF 檔案的函式庫。這些函式庫共同提供在 C# 應用程式中處理 Word 與 PDF 文件的全面解決方案。

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