使用IRONWORD

如何在 C# 中創建無需 Office 互操作性的 Word 文件

發佈 2024年3月12日
分享:

Microsoft Word 文件被廣泛用於各種用途,從正式的商業報告到個人信函。在 C# 中,開發人員經常需要以程式方式生成 Microsoft Word 文件。Windows 應用程式開發人員傳統上使用 Microsoft Office Interop 來生成和創建 Word 文件,並使用 C# 進行操作。

然而,這種方法並不是對所有人都完全可用,並且可能會遇到開發人員使用其他作業系統或在 Linux 機器上無法使用 Microsoft Office 介面。在這些情況下,開發人員需要探索其他能夠在不同平臺上獨立運作的庫。一個用於以程式方式處理 Word 文件的強大庫是 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 文檔。

如何在 C# 中無需使用 Office Interop 創建 Word 文件

  1. 創建一個新的 C# 項目。

  2. 安裝 IronWord 資料庫。

  3. 使用 IronWord 資料庫創建一個 Word 文檔。

  4. 向現有的文檔添加內容。

  5. 保存創建的 Word 文檔。

  6. 打開並顯示創建的 Word 文檔。

前提條件:

  1. Visual Studio: 確保已安裝 Visual Studio 或任何其他的 C# 開發環境。

  2. NuGet 包管理器: 確保能夠使用 NuGet 管理項目中的包。

步驟 1:建立新的 C# 專案

建立新的 C# 主控台應用程式,或是使用您想要生成 Word 文件的現有專案。

選擇主控台應用程式模板並點擊下一步。

如何在 C# 中創建不使用 Office Interop 的 Word 文件:圖 1 - 用於創建新專案的控制台應用程式範本

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

如何在 C# 中不使用 Office Interop 創建 Word 文件:圖 2 - 配置包含解決方案和項目名稱的項目

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

如何在 C# 中不使用 Office Interop 創建 Word 文檔:圖 3 - 使用正確的 .NET 版本創建項目

步驟 2:安裝 IronWord 函式庫

打開您的 C# 專案並安裝 IronWord 使用 NuGet 套件管理器控制台的程式庫:

Install-Package IronWord -Version 2024.1.2

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

如何在 C# 中創建無需 Office 互操作的 Word 文件:圖 4 - 使用 VS 套件管理器安裝 IronWord

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

讓我們從使用 IronWord 函式庫建立 Word 文件的簡單範例開始。以下代碼展示了如何建立一個包含單段落文字 "Hello, World" 的基本 Word 文件。!請提供您想要翻譯的內容。

using IronWord;
using IronWord.Models;
// Create textrun instance
TextRun textRun = new TextRun("Hello, World!");
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);
// Create a new Word document object
WordDocument doc = new WordDocument(paragraph);
// Export docx
doc.SaveAs("example.docx"); // save docx file to disk
using IronWord;
using IronWord.Models;
// Create textrun instance
TextRun textRun = new TextRun("Hello, World!");
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);
// Create a new Word document object
WordDocument doc = new WordDocument(paragraph);
// Export docx
doc.SaveAs("example.docx"); // save docx file to disk
Imports IronWord
Imports IronWord.Models
' Create textrun instance
Private textRun As New TextRun("Hello, World!")
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)
' Create a new Word document object
Dim doc As New WordDocument(paragraph)
' Export docx
doc.SaveAs("example.docx") ' save docx file to disk
VB   C#

執行上述程式碼範例後,將建立新的檔案 example.docx,輸出結果如下。

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

這是一個使用 IronWord 生成 Word 文件的基本範例。如需更多資訊,您可以參考文檔 這裡.

向 Word 文件添加帶有樣式的段落

現在我們已經知道如何使用 IronWord 創建一個簡單的 Word 文件,讓我們來添加段落和帶有樣式的文本。

TextRun 也可以接受樣式數據,增強文本的視覺展示效果。文本可以設置為刪除線、加粗、斜體和下劃線等樣式。

修改並添加以下代碼到你之前製作的程序中。

using IronWord;
using IronWord.Models;
// Create textrun
TextRun textRun = new TextRun("Hello, World!"); // add string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);
// Configure text
TextRun introText = new TextRun("This is an example paragraph with italic and bold styling."); // add string or text
TextStyle italicStyle = new TextStyle()
{
    IsItalic = true
};
TextRun italicText = new TextRun("Italic example sentence.", italicStyle); 
// add italic string
TextStyle boldStyle = new TextStyle()
{
    IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle); 
// add bold string
// Add text
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);
// Create a new Word document
WordDocument doc = new WordDocument(paragraph);
// Export docx document
doc.SaveAs("example.docx");// docx file save in EXE location
using IronWord;
using IronWord.Models;
// Create textrun
TextRun textRun = new TextRun("Hello, World!"); // add string
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);
// Configure text
TextRun introText = new TextRun("This is an example paragraph with italic and bold styling."); // add string or text
TextStyle italicStyle = new TextStyle()
{
    IsItalic = true
};
TextRun italicText = new TextRun("Italic example sentence.", italicStyle); 
// add italic string
TextStyle boldStyle = new TextStyle()
{
    IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle); 
// add bold string
// Add text
paragraph.AddTextRun(introText);
paragraph.AddTextRun(italicText);
paragraph.AddTextRun(boldText);
// Create a new Word document
WordDocument doc = new WordDocument(paragraph);
// Export docx document
doc.SaveAs("example.docx");// docx file save in EXE location
Imports IronWord
Imports IronWord.Models
' Create textrun
Private textRun As New TextRun("Hello, World!") ' add string
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)
' Configure text
Dim introText As New TextRun("This is an example paragraph with italic and bold styling.") ' add string or text
Dim italicStyle As New TextStyle() With {.IsItalic = True}
Dim italicText As New TextRun("Italic example sentence.", italicStyle)
' add italic string
Dim boldStyle As New TextStyle() With {.IsBold = True}
Dim boldText As New TextRun("Bold example sentence.", boldStyle)
' add bold string
' Add text
paragraph.AddTextRun(introText)
paragraph.AddTextRun(italicText)
paragraph.AddTextRun(boldText)
' Create a new Word document
Dim doc As New WordDocument(paragraph)
' Export docx document
doc.SaveAs("example.docx") ' docx file save in EXE location
VB   C#

將表格添加到 Word 文件中

為了清晰地表示數據,也可以使用網格形式來表示數據。當數據排列成網格狀時,稱為表格。使用 IronWord,我們可以將表格和圖片添加到 Word 文件中,如下所示:

using IronWord;
using IronWord.Models;
// Create table cell
TableCell cell = new TableCell();
TextRun textRun = new TextRun();
textRun.Text = "Sample text";
// Add textrun to the cell
cell.AddContent(new Paragraph(textRun));
// Configure border style 
BorderStyle borderStyle = new BorderStyle();
borderStyle.BorderColor = new IronColor(IronSoftware.Drawing.Color.Black);
borderStyle.BorderValue = IronWord.Models.Enums.BorderValues.Thick;
borderStyle.BorderSize = 5;
// Configure table border
TableBorders tableBorders = new TableBorders() { 
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle,
};
cell.Borders = tableBorders;
// Create row and add cell
TableRow row = new TableRow();
row.AddCell(cell); // add cell
row.AddCell(cell); // add cell
// Create table and add row
Table table = new Table();
table.AddRow(row);
// Generate document from the table
WordDocument doc = new WordDocument(table);
// Export Word document
doc.SaveAs("Document.docx"); // docx file save in EXE location
using IronWord;
using IronWord.Models;
// Create table cell
TableCell cell = new TableCell();
TextRun textRun = new TextRun();
textRun.Text = "Sample text";
// Add textrun to the cell
cell.AddContent(new Paragraph(textRun));
// Configure border style 
BorderStyle borderStyle = new BorderStyle();
borderStyle.BorderColor = new IronColor(IronSoftware.Drawing.Color.Black);
borderStyle.BorderValue = IronWord.Models.Enums.BorderValues.Thick;
borderStyle.BorderSize = 5;
// Configure table border
TableBorders tableBorders = new TableBorders() { 
    TopBorder = borderStyle,
    RightBorder = borderStyle,
    BottomBorder = borderStyle,
    LeftBorder = borderStyle,
};
cell.Borders = tableBorders;
// Create row and add cell
TableRow row = new TableRow();
row.AddCell(cell); // add cell
row.AddCell(cell); // add cell
// Create table and add row
Table table = new Table();
table.AddRow(row);
// Generate document from the table
WordDocument doc = new WordDocument(table);
// Export Word document
doc.SaveAs("Document.docx"); // docx file save in EXE location
Imports IronWord
Imports IronWord.Models
' Create table cell
Private cell As New TableCell()
Private textRun As New TextRun()
textRun.Text = "Sample text"
' Add textrun to the cell
cell.AddContent(New Paragraph(textRun))
' Configure border style 
Dim borderStyle As New BorderStyle()
borderStyle.BorderColor = New IronColor(IronSoftware.Drawing.Color.Black)
borderStyle.BorderValue = IronWord.Models.Enums.BorderValues.Thick
borderStyle.BorderSize = 5
' Configure table border
Dim tableBorders As New TableBorders() With {
	.TopBorder = borderStyle,
	.RightBorder = borderStyle,
	.BottomBorder = borderStyle,
	.LeftBorder = borderStyle
}
cell.Borders = tableBorders
' Create row and add cell
Dim row As New TableRow()
row.AddCell(cell) ' add cell
row.AddCell(cell) ' add cell
' Create table and add row
Dim table As New Table()
table.AddRow(row)
' Generate document from the table
Dim doc As New WordDocument(table)
' Export Word document
doc.SaveAs("Document.docx") ' docx file save in EXE location
VB   C#

在上面的範例中,我們使用邊框在Word文檔中添加了一個表格。

將圖片新增到 Word 文件中

圖片可以提升文件的呈現效果,並增加更多的顏色和視覺吸引力。

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

using IronWord;
using IronWord.Models;
// Load new document
WordDocument doc = new WordDocument();
// Configure image
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg");
image.Width = 200; // In unit pixel (px)
image.Height = 200; // In unit pixel (px)
Paragraph paragraph = new Paragraph();
// Add image
paragraph.AddImage(image);
// Add paragraph 
doc.AddParagraph(paragraph);
// Export docx
doc.SaveAs("save_document.docx"); // docx file
using IronWord;
using IronWord.Models;
// Load new document
WordDocument doc = new WordDocument();
// Configure image
IronWord.Models.Image image = new IronWord.Models.Image("SalesChart.jpg");
image.Width = 200; // In unit pixel (px)
image.Height = 200; // In unit pixel (px)
Paragraph paragraph = new Paragraph();
// Add image
paragraph.AddImage(image);
// Add paragraph 
doc.AddParagraph(paragraph);
// Export docx
doc.SaveAs("save_document.docx"); // docx file
Imports IronWord
Imports IronWord.Models
' Load new document
Private doc As New WordDocument()
' Configure image
Private image As New IronWord.Models.Image("SalesChart.jpg")
image.Width = 200 ' In unit pixel (px)
image.Height = 200 ' In unit pixel (px)
Dim paragraph As New Paragraph()
' Add image
paragraph.AddImage(image)
' Add paragraph 
doc.AddParagraph(paragraph)
' Export docx
doc.SaveAs("save_document.docx") ' docx file
VB   C#

在這裡,我們使用 IronWord.Models.Image,將高度和寬度為 200 像素的圖像添加到段落中。

授權 (免費試用)

IronWord 需要許可證才能使用。可以從 Iron Software 網站獲取試用金鑰 這裡這個密鑰需要放置在 appsettings.json。

{
    "IronWord.LicenseKey":"IRONWORD.MYLICENSE.KEY.TRIAL"
}
{
    "IronWord.LicenseKey":"IRONWORD.MYLICENSE.KEY.TRIAL"
}
If True Then
	"IronWord.LicenseKey":"IRONWORD.MYLICENSE.KEY.TRIAL"
End If
VB   C#

提供您的電子郵件以獲取試用授權。提交郵件ID後,授權金鑰將通過電子郵件發送。

如何在 C# 中創建不需要 Office 互操作的 Word 文件:圖6 - 試用表單成功提交後的彈出窗口

結論

使用 C# 創建 Word 文件 IronWord library 提供了一種靈活且高效的方式來生成文檔,無需依賴 Microsoft Office。無論您需要創建簡單的信件還是包含表格和圖像的複雜報告,IronWord 都能讓您通過程式來實現。本文提供了關於創建 Word 文檔的全面教程。通過 IronWord,您可以自動化創建 Word 文檔,使您的 C# 應用程序更加多樣化和高效。

而對於需要處理與其生成的 Word 文檔一起使用的 PDF 文件的開發人員,只需查看由 Iron Software 生產的另一個 C# 庫 IronPDF。要查看,請點擊 這裡.

< 上一頁
如何在 VB .NET 中程式化地創建 Word 文件
下一個 >
如何在 C# 中读取带有格式的 Word 文档

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 5,614 查看許可證 >