使用IRONWORD

如何在 C# 中读取带有格式的 Word 文档

發佈 2024年2月22日
分享:

Microsoft Word 文件通常包含豐富的格式,例如字體、樣式和各種元素,使它們在視覺上具有吸引力。IronWord 是來自 Iron Software 的強大庫 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 文件並保留格式

  1. 安裝 IronWord 庫以讀取 Word 文件。

  2. 使用 IronWord 庫中的 WordDocument 類加載輸入文件 'sample.docx'。

  3. 使用加載的 Word 文件並讀取保留格式的段落。

  4. 在控制台輸出中顯示提取數據和格式信息。

先決條件

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

  2. 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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract Formatting details
                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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract Formatting details
                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
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text ' read the text
				' Extract Formatting details
				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
VB   C#

上述程式碼使用 IronWord 函式庫中的 WordDocument 建構函數方法讀取 Word 文件

輸出

如何在 C# 中讀取帶有格式的 Word 文件:圖 7 - 前面代碼的控制台輸出

解釋

  1. 開啟 Word 文件:使用 IronWord 中的 WordDocument 來載入 Word 文件。

  2. 迭代段落和執行:使用巢狀迴圈來迭代段落和執行。執行表示具有特定格式的文字部分。

  3. 提取文字和格式:從每個執行中提取文字內容並檢查格式屬性。在此範例中,我們演示了如何提取字體大小和粗體格式。

  4. 處理例外狀況:使用 try-catch 區塊來處理任何例外狀況並將其輸出。

載入的文件可用於打印文件,我們還可以在樣式物件中更改字體顏色。

從 Word 文件中讀取表格

我們也可以從 Word 文件中讀取表格。將以下程式碼片段添加到程式中。

using IronWord;
class Program
{
    static void Main()
    {
        try
        {
            // Load existing docx
            var sampleDoc = new WordDocument("sample.docx");
            var paragraphs = sampleDoc.Paragraphs;
            // 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");
            var paragraphs = sampleDoc.Paragraphs;
            // 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")
			Dim paragraphs = sampleDoc.Paragraphs
			' 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
VB   C#

我們在這裡使用 WordDocument 類的 get/set 方法 Tables 來獲取文檔中的所有表格,然後遍歷它們並打印內容。

為現有文字添加樣式

我們可以使用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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract Formatting details
                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 formating of the text
            var style = new TextStyle()
            {
                FontFamily = "Caveat",
                FontSize = 72,
                TextColor = new IronColor(Color.Blue), // blue color
                IsBold = true,
                IsItalic = true,
                IsUnderline = true,
                IsSuperscript = false,
                IsStrikethrough = true,
                IsSubscript = false
            };
            paragraphs [1].FirstTextRun.Style = style;
            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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract Formatting details
                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 formating of the text
            var style = new TextStyle()
            {
                FontFamily = "Caveat",
                FontSize = 72,
                TextColor = new IronColor(Color.Blue), // blue color
                IsBold = true,
                IsItalic = true,
                IsUnderline = true,
                IsSuperscript = false,
                IsStrikethrough = true,
                IsSubscript = false
            };
            paragraphs [1].FirstTextRun.Style = style;
            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
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text ' read the text
				' Extract Formatting details
				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 formating of the text
			Dim style = New TextStyle() With {
				.FontFamily = "Caveat",
				.FontSize = 72,
				.TextColor = New IronColor(Color.Blue),
				.IsBold = True,
				.IsItalic = True,
				.IsUnderline = True,
				.IsSuperscript = False,
				.IsStrikethrough = True,
				.IsSubscript = False
			}
			paragraphs (1).FirstTextRun.Style = style
			sampleDoc.SaveAs("sample2.docx")
		Catch ex As Exception
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

我們在此創建一個 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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract the formatting details
                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(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
            TextRun introText = new TextRun("This is an example newParagraph 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 text
            newParagraph.AddTextRun(introText);
            newParagraph.AddTextRun(italicText);
            newParagraph.AddTextRun(boldText);
            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;
            foreach (var paragraph in paragraphs)
            {
                var textRun = paragraph.FirstTextRun;
                var text = textRun.Text; // read the text
                // Extract the formatting details
                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(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
            TextRun introText = new TextRun("This is an example newParagraph 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 text
            newParagraph.AddTextRun(introText);
            newParagraph.AddTextRun(italicText);
            newParagraph.AddTextRun(boldText);
            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
			For Each paragraph In paragraphs
				Dim textRun = paragraph.FirstTextRun
				Dim text = textRun.Text ' read the text
				' Extract the formatting details
				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(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
			Dim introText As New TextRun("This is an example newParagraph 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 text
			newParagraph.AddTextRun(introText)
			newParagraph.AddTextRun(italicText)
			newParagraph.AddTextRun(boldText)
			sampleDoc.SaveAs("sample2.docx")
		Catch ex As Exception
			Console.WriteLine($"An error occurred: {ex.Message}")
		End Try
	End Sub
End Class
VB   C#

在這裡,我們正在創建帶有樣式資訊的新 TextRun 和 Paragraph 物件,並將它們添加到已載入的 Word 文件中。

授權 (免費試用)

IronWord這個密鑰需要放置在 appsettings.json。

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

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

如何在 C# 中帶格式閱讀 Word 文件:圖 8 - 成功提交試用表單

結論

IronWord 提供了一種在C#中讀取格式化Word文件的便捷方式。根據您的具體需求和您正在處理的文件的複雜性,擴展提供的代碼。本教程作為整合的起點 IronWord 進入您的 C# 應用程式以進行 Word 文件處理。

< 上一頁
如何在 C# 中創建無需 Office 互操作性的 Word 文件
下一個 >
3 個 C# Word 函式庫(給開發者的更新列表)

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

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