如何使用 C# 將 Word 文件閱讀時保留格式
Microsoft Word文件被廣泛用於各種目的,從正式的商業報告到個人信件。 在C#中,開發者經常需要以程式方式生成Microsoft Word文件。 Windows應用程式開發者傳統上使用Microsoft Office Interop來生成和建立使用C#的Word文件。
然而,這種方式不適合所有人,開發者可能會在操作系統或Linux計算機上使用,這裡沒有Microsoft Office介面。 在這些情況下,開發者必須探索能在不同平台上獨立工作的其他程式庫。 其中一個功能強大的程式庫是IronWord,來自Iron Software。
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文件。
How to Create Word Documents Without Office Interop in C
- 建立一個新的C#專案。
- 安裝IronWord程式庫。
- 使用IronWord程式庫建立Word文件。
- 向現有文件新增內容。
- 保存建立的Word文件。
- 打開並顯示建立的Word文件。
先決條件:
- Visual Studio:請確保您已安裝Visual Studio或任何其他C#開發環境。
- NuGet包管理器:確保您可以在專案中使用NuGet來管理包。
步驟1:建立新的C#專案
建立一個新的C#控制台應用程式或使用您想要生成Word文件的現有專案。
選擇控制台應用程式範本然後點擊下一步。

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

選擇.NET版本並點擊"建立"。

步驟2:安裝IronWord程式庫
打開您的C#專案並使用NuGet包管理控制台安裝IronWord程式庫:
Install-Package IronWord -Version 2024.1.2
可使用Visual Studio包管理器來安裝NuGet包,如下所示。

步驟3:使用IronWord程式庫建立並保存Word文件
讓我們從使用IronWord程式庫建立Word文件的簡單範例開始。 以下程式碼演示瞭如何建立一個包含文字"Hello, World!"的單一段落的基本Word文件。
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
執行上述程式碼範例後,將生成新的文件文件example.docx,輸出如下所示。

這是一個使用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
在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
在上述範例中,我們使用邊框向Word文件新增了一個表格。
在Word文件中新增圖片
圖片可以提升文件的展示效果,增加更多顏色和視覺吸引力。
圖片可以程式化地新增到Word文件中,使用IronWord如下程式碼所示:
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
在這裡,我們使用IronWord.Models.Image向段落新增高度和寬度為200像素的圖片。
授權(免費試用可用)
使用IronWord需要許可。 從Iron Software網站獲取試用金鑰。此金鑰需要放置在appsettings.json。
{
"IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}
請提供您的電子郵件以獲取試用授權。 提交您的電子郵件ID後,金鑰將通過電子郵件傳遞給您。

結論
使用IronWord程式庫在C#中建立Word文件提供了一種靈活而有效的生成文件方式,不依賴於Microsoft Office。無論您需要建立簡單的信件還是包含表格和圖像的複雜報告,IronWord可以程式化地實現這一點。 本文提供了全面的Word文件建立教程。 使用IronWord,您可以自動化Word文件的建立,使您的C#應用程式更加多樣化和高效。
尋找與生成的Word文件一起工作的PDF文件操作的開發者,不妨考慮IronPDF,這是Iron Software另一個C#程式庫。
常見問題
如何在不使用 Microsoft Office Interop 的情況下在 C# 中建立 Word 文件?
您可以透過使用 IronWord 程式庫在不使用 Microsoft Office Interop 的情況下在 C# 中建立 Word 文件。此程式庫允許您以程式方式生成、編輯和保存 Word 文件,無需安裝 Microsoft Office。
using IronWord 比 Microsoft Office Interop 有哪些優勢?
IronWord 提供了靈活性,它可以運行在如 Linux 這樣 Microsoft Office Interop 不可用的非 Windows 平台上。它也消除了必須安裝 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 允許您使用 TextRun 和 TextStyle 類來新增樣式文字。這些類使您能夠對 Word 文件中的特定文字片段應用如粗體、斜體和下劃線樣式。
using 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 文件提供了全面的解決方案。



