如何使用 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程式庫:
可使用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.docxImports 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.docxImports 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.docxImports 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.docxImports 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#程式庫。

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

