3 個 C# Word 庫(為開發人員更新的列表)
Microsoft Word文件通常包含豐富的格式,例如字體、樣式和各種元素,使其具有視覺吸引力。 IronWord是來自Iron Software 的一個強大程式庫,具有直觀的C#和VB.NET Word及Docx文件API。 不需要安裝Microsoft Office或Word Interop即可構建、編輯和匯出Word文件。 IronWord完全支援.NET 8、7、6、Framework、Core和Azure。 這意味著該程式庫不需要在機器上安裝Word即可獨立讀取文件。 如果您使用C#並需要在保留其格式的情況下讀取Word文件,此教學將通過使用IronWord程式庫引導您完成這一過程。
如何在C#中讀取具有格式的Word文件
- 安裝IronWord程式庫以讀取Word文件。
- 使用IronWord程式庫中的
WordDocument類載入輸入Word文件'sample.docx'。 - 使用已載入的Word文件讀取格式化的段落。
- 在控制台輸出中顯示具有格式資訊的提取資料。
先決條件
- Visual Studio:請確保您已安裝Visual Studio或任何其他C#開發環境。
- NuGet包管理器:確保您能夠使用NuGet管理項目中的包
步驟1:建立新的C#專案
建立新的C#控制台應用程式或使用現有的項目,在那里您希望讀取Word文件。
選擇控制台應用程式範本然後點擊下一步。
如何在C#中讀取具有格式的Word文件:圖1 - 建立新的C#項目
單擊"下一步"按鈕以提供解決方案名稱、項目名稱和程式碼的路徑。
如何在C#中讀取具有格式的Word文件:圖2 - 配置新項目
然後選擇所需的.NET版本。 最好的做法是始終選擇可用的最新版本,雖然如果您的項目有特定需求,那麼使用必要的.NET版本。
如何在C#中讀取具有格式的Word文件:圖3 - 選擇必要的.NET版本型別
步驟2:安裝IronWord程式庫
打開您的C#項目並使用NuGet包管理器控制台安裝IronWord程式庫:
Install-Package IronWord
NuGet包也可以使用Visual Studio的NuGet包管理器進行安裝,如下所示。
如何在C#中讀取具有格式的Word文件:圖4 - 通過NuGet包管理器安裝IronWord
步驟3:讀取具有格式的Word文件
要讀取Word文件,首先我們需要建立一個新文件,然後向其中新增一些內容,如下所示。
如何在C#中讀取具有格式的Word文件:圖5 - 建立的一個樣本文件
現在將文件保存到項目目錄,並更改文件屬性以將其複製到輸出目錄。
如何在C#中讀取具有格式的Word文件:圖6 - 文件屬性應該是這樣的
現在將下面的程式碼片段新增到program.cs文件中:
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through each paragraph in the Word document
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through each paragraph in the Word document
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Imports Microsoft.VisualBasic
Imports IronWord
Friend Class Program
Shared Sub Main()
Try
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through each paragraph in the Word document
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract Formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
Console.WriteLine($vbTab & "Text: {text}")
End If
Next paragraph
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Class
上述程式碼使用IronWord程式庫類的WordDocument構造方法讀取Word文件。
輸出
如何在C#中讀取具有格式的Word文件:圖7 - 從前面的程式碼到控制台輸出
說明
- 打開Word文件:使用IronWord的
WordDocument載入Word文件。 - 遍歷段落和運行:使用巢狀迴圈遍歷段落和運行。 運行代表具有特定格式的文字部分。
- 提取文字和格式:從每個運行中提取文字內容,並檢查格式屬性。 在此範例中,我們演示了如何提取字體大小和粗體格式。
- 處理異常:使用try-and-catch塊處理任何異常並列印出來。
已載入的文件可以用於列印文件,我們還可以在樣式對像中更改字體顏色。
從Word文件中讀取表格
我們還可以從Word文件中讀取表格。 將下面的程式碼片段新增到程式中。
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
// Read Tables
var tables = sampleDoc.Tables;
foreach (var table in tables)
{
var rows = table.Rows;
foreach (var row in rows)
{
foreach (var cell in row.Cells)
{
var contents = cell.Contents;
contents.ForEach(x => Console.WriteLine(x));
// Print cell contents
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
using IronWord;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
// Read Tables
var tables = sampleDoc.Tables;
foreach (var table in tables)
{
var rows = table.Rows;
foreach (var row in rows)
{
foreach (var cell in row.Cells)
{
var contents = cell.Contents;
contents.ForEach(x => Console.WriteLine(x));
// Print cell contents
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Imports IronWord
Friend Class Program
Shared Sub Main()
Try
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
' Read Tables
Dim tables = sampleDoc.Tables
For Each table In tables
Dim rows = table.Rows
For Each row In rows
For Each cell In row.Cells
Dim contents = cell.Contents
contents.ForEach(Sub(x) Console.WriteLine(x))
' Print cell contents
Next cell
Next row
Next table
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Class
在此我們使用WordDocument類獲取文件中的所有表格,然後遍歷它們並列印內容。
為現有文字新增樣式
我們可以使用IronWord程式庫將新的樣式資訊新增到現有的Word文件中,如以下程式碼片段所示。
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Change the formatting of the text
var style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].FirstTextRun.Style = style;
// Save the document with the new style applied
sampleDoc.SaveAs("sample2.docx");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load existing docx
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract Formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Change the formatting of the text
var style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].FirstTextRun.Style = style;
// Save the document with the new style applied
sampleDoc.SaveAs("sample2.docx");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Imports Microsoft.VisualBasic
Imports IronWord
Imports IronWord.Models
Friend Class Program
Shared Sub Main()
Try
' Load existing docx
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through paragraphs
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract Formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
Console.WriteLine($vbTab & "Text: {text}")
End If
Next paragraph
' Change the formatting of the text
Dim style = New TextStyle() With {
.FontFamily = "Caveat",
.FontSize = 72,
.TextColor = New IronColor(System.Drawing.Color.Blue),
.IsBold = True,
.IsItalic = True,
.IsUnderline = True,
.IsSuperscript = False,
.IsStrikethrough = True,
.IsSubscript = False
}
paragraphs(1).FirstTextRun.Style = style
' Save the document with the new style applied
sampleDoc.SaveAs("sample2.docx")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Class
在此我們建立一個TextStyle並將其新增到現有的段落對像中。
為Word文件新增新的樣式內容
我們可以像下面的程式碼片段那樣將新內容新增到載入的Word文件中。
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load Word Document
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract the formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Add TextRun with Style to Paragraph
TextRun blueTextRun = new TextRun();
blueTextRun.Text = "Add text using IronWord";
blueTextRun.Style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].AddTextRun(blueTextRun);
// Add New Content to the Word file and save
Paragraph newParagraph = new Paragraph();
TextRun newTextRun = new TextRun("New Add Information");
newParagraph.AddTextRun(newTextRun);
// Configure the text with different styles
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);
TextStyle boldStyle = new TextStyle()
{
IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);
// Add the styled text to the paragraph
newParagraph.AddTextRun(introText);
newParagraph.AddTextRun(italicText);
newParagraph.AddTextRun(boldText);
// Save the modified document
sampleDoc.SaveAs("sample2.docx");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
try
{
// Load Word Document
var sampleDoc = new WordDocument("sample.docx");
var paragraphs = sampleDoc.Paragraphs;
// Iterate through paragraphs
foreach (var paragraph in paragraphs)
{
var textRun = paragraph.FirstTextRun;
var text = textRun.Text; // Read text content
// Extract the formatting details if available
if (textRun.Style != null)
{
var fontSize = textRun.Style.FontSize; // Font size
var isBold = textRun.Style.IsBold;
Console.WriteLine($"\tText: {text}, FontSize: {fontSize}, Bold: {isBold}");
}
else
{
// Print text without formatting details
Console.WriteLine($"\tText: {text}");
}
}
// Add TextRun with Style to Paragraph
TextRun blueTextRun = new TextRun();
blueTextRun.Text = "Add text using IronWord";
blueTextRun.Style = new TextStyle()
{
FontFamily = "Caveat",
FontSize = 72,
TextColor = new IronColor(System.Drawing.Color.Blue), // Blue color
IsBold = true,
IsItalic = true,
IsUnderline = true,
IsSuperscript = false,
IsStrikethrough = true,
IsSubscript = false
};
paragraphs[1].AddTextRun(blueTextRun);
// Add New Content to the Word file and save
Paragraph newParagraph = new Paragraph();
TextRun newTextRun = new TextRun("New Add Information");
newParagraph.AddTextRun(newTextRun);
// Configure the text with different styles
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);
TextStyle boldStyle = new TextStyle()
{
IsBold = true
};
TextRun boldText = new TextRun("Bold example sentence.", boldStyle);
// Add the styled text to the paragraph
newParagraph.AddTextRun(introText);
newParagraph.AddTextRun(italicText);
newParagraph.AddTextRun(boldText);
// Save the modified document
sampleDoc.SaveAs("sample2.docx");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Imports Microsoft.VisualBasic
Imports IronWord
Imports IronWord.Models
Friend Class Program
Shared Sub Main()
Try
' Load Word Document
Dim sampleDoc = New WordDocument("sample.docx")
Dim paragraphs = sampleDoc.Paragraphs
' Iterate through paragraphs
For Each paragraph In paragraphs
Dim textRun = paragraph.FirstTextRun
Dim text = textRun.Text ' Read text content
' Extract the formatting details if available
If textRun.Style IsNot Nothing Then
Dim fontSize = textRun.Style.FontSize ' Font size
Dim isBold = textRun.Style.IsBold
Console.WriteLine($vbTab & "Text: {text}, FontSize: {fontSize}, Bold: {isBold}")
Else
' Print text without formatting details
Console.WriteLine($vbTab & "Text: {text}")
End If
Next paragraph
' Add TextRun with Style to Paragraph
Dim blueTextRun As New TextRun()
blueTextRun.Text = "Add text using IronWord"
blueTextRun.Style = New TextStyle() With {
.FontFamily = "Caveat",
.FontSize = 72,
.TextColor = New IronColor(System.Drawing.Color.Blue),
.IsBold = True,
.IsItalic = True,
.IsUnderline = True,
.IsSuperscript = False,
.IsStrikethrough = True,
.IsSubscript = False
}
paragraphs(1).AddTextRun(blueTextRun)
' Add New Content to the Word file and save
Dim newParagraph As New Paragraph()
Dim newTextRun As New TextRun("New Add Information")
newParagraph.AddTextRun(newTextRun)
' Configure the text with different styles
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)
Dim boldStyle As New TextStyle() With {.IsBold = True}
Dim boldText As New TextRun("Bold example sentence.", boldStyle)
' Add the styled text to the paragraph
newParagraph.AddTextRun(introText)
newParagraph.AddTextRun(italicText)
newParagraph.AddTextRun(boldText)
' Save the modified document
sampleDoc.SaveAs("sample2.docx")
Catch ex As Exception
Console.WriteLine($"An error occurred: {ex.Message}")
End Try
End Sub
End Class
在此我們建立新的Paragraph物件,並將樣式資訊新增到載入的Word文件中。
授權(免費試用可用)
獲取您的IronWord免費試用授權金鑰。 此金鑰需要放在appsettings.json中。
{
"IronWord.LicenseKey": "IRONWORD.MYLICENSE.KEY.TRIAL"
}
請提供您的電子郵件以獲取試用授權。 提交您的電子郵件ID後,金鑰將通過電子郵件傳遞給您。
如何在C#中讀取具有格式的Word文件:圖8 - 成功提交了試用表格
結論
IronWord 提供了一種便捷的方法來在C#中讀取具有格式的Word文件。 基於您的具體需求以及您正在處理的文件的復雜性擴展提供的程式碼。 本教學作為將IronWord整合到您的C#應用程式中用於Word文件處理的起點。
常見問題
我如何在C#中讀取具有格式的Word文件?
要在C#中讀取具有格式的Word文件,請使用IronWord程式庫。首先通過NuGet套件管理器安裝IronWord。使用WordDocument類載入文件,並迭代段落以提取文字和格式詳細資訊。
為讀取Word文件設置C#專案的步驟是什麼?
要設置讀取Word文件的C#專案,請安裝Visual Studio或其他C#開發環境。使用NuGet套件管理器將IronWord新增到您的專案中。使用WordDocument類載入Word文件以存取其內容。
如何在C#中處理讀取Word文件時的異常?
在C#中使用IronWord讀取Word文件時,通過在文件處理程式碼周圍實現try-catch塊來處理異常。這將有助於管理運行時錯誤並確保應用程式的穩健行為。
我可以使用C#從Word文件中讀取表格嗎?
是的,您可以使用IronWord在C#中從Word文件中讀取表格。通過WordDocument類的Tables屬性存取表格,並在需要時迭代表格資料。
如何在C#中修改Word文件中的文字樣式?
使用IronWord修改Word文件中的文字樣式,方法是建立TextStyle物件,並將其應用於特定的文字運行或段落。這允許您自定義字體、大小和其他樣式屬性。
在C#中可以向Word文件新增新內容嗎?
是的,您可以使用IronWord在C#中向Word文件中新增新內容。建立TextRun和Paragraph物件,在保存更改之前將樣式化內容新增到文件中。
如何在C#中保存Word文件的修改?
使用IronWord編輯Word文件後,通過在WordDocument實例上調用Save方法保存更改。指定文件路徑以建立應用修改的新文件。
處理Word文件我是否需要安裝Microsoft Office?
不,您不需要安裝Microsoft Office來使用IronWord在C#中處理Word文件。該程式庫獨立於Microsoft Office,允許您直接處理Word文件。
.NET版本中哪些與Word處理程式庫相容?
IronWord能夠相容於多個.NET版本,包括.NET 8、7、6、Framework、Core和Azure。這確保它滿足各種專案的需求和環境。
如何獲得C#中Word處理程式庫的試用授權?
要獲得IronWord的試用授權,請存取Iron Software網站並提供您的電子郵件地址。您將通過電子郵件收到試用授權金鑰,可以將其新增到您的appsettings.json文件中。



