跳過到頁腳內容
使用 IRONWORD

如何以 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 文檔

  1. 安裝 IronWord 庫以讀取 Word 文件。
  2. 使用 IronWord 庫中的WordDocument類別載入輸入 Word 文件"sample.docx"。
  3. 使用載入的 Word 文件閱讀帶有格式的段落。
  4. 在控制台輸出中顯示擷取的資料及其格式資訊。

先決條件

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

  1. 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

也可以使用 Visual Studio 的 NuGet 套件管理器安裝 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
$vbLabelText   $csharpLabel

上述程式碼使用 IronWord 函式庫類別WordDocument建構函式方法讀取 Word 文件。

輸出

如何在 C# 中讀取帶有格式的 Word 文件:圖 7 - 上一段程式碼的控制台輸出

說明

1.開啟 Word 文件:使用 IronWord 中的WordDocument載入 Word 文件。 2.遍歷段落和段落:使用巢狀循環遍歷段落和段落。 樂段代表具有特定格式的文字部分。 3.提取文字和格式:從每次運行中提取文字內容並檢查格式屬性。 在這個例子中,我們示範如何提取字體大小和粗體格式。 4.處理異常:使用 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
$vbLabelText   $csharpLabel

這裡我們使用WordDocument類別的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;

            // 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
$vbLabelText   $csharpLabel

這裡我們建立一個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
$vbLabelText   $csharpLabel

在這裡,我們將建立帶有樣式資訊的TextRunParagraph對象,並將它們新增至已載入的 Word 文件中。

授權(可免費試用)

取得您的 IronWord 免費試用授權金鑰。 此 key 需要放在 appsettings.json 中。

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

提供您的電子郵件以取得試用授權。 提交您的電子郵件地址後,金鑰將透過電子郵件發送給您。

如何在 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 Package Manager 將 IronWord 加入專案。使用 WordDocument 類載入 Word 文件以存取其內容。

在 C# 中閱讀 Word 文件時,如何處理異常?

使用 IronWord 以 C# 語言閱讀 Word 文件時,請透過在文件處理程式碼周圍執行 try-catch 區塊來處理異常。這將有助於管理執行時錯誤,並確保穩健的應用程式行為。

我可以使用 C# 從 Word 文件讀取表格嗎?

是的,您可以使用 C# 中的 IronWord 從 Word 文件讀取表格。透過 WordDocument 類的 Tables 屬性存取表格,並根據需要遍歷表格資料。

如何使用 C# 修改 Word 文件中的文字樣式?

使用 IronWord 修改 Word 文件中的文字樣式,方法是建立 TextStyle 物件,並將其套用至特定的文字運行或段落。這可讓您自訂字型、大小和其他樣式屬性。

是否可以在 C# 中為 Word 文件新增內容?

是的,您可以使用 C# 中的 IronWord 為 Word 文件新增內容。在儲存您的變更之前,建立 TextRunParagraph 物件,以在文件中加入樣式化的內容。

如何在 C# 中保存對 Word 文檔的修改?

使用 IronWord 編輯完 Word 文檔後,在 WordDocument 實體上呼叫 Save 方法來儲存您的變更。指定檔案路徑,以建立一個新的文件,並應用所做的修改。

我需要安裝 Microsoft Office 才能用 C# 處理 Word 文件嗎?

不,您不需要安裝 Microsoft Office 即可使用 IronWord 以 C# 處理 Word 文件。該函式庫的功能獨立於 Microsoft Office,可讓您直接處理 Word 檔案。

哪些 .NET 版本與 Word 處理庫相容?

IronWord 與多種 .NET 版本相容,包括 .NET 8、7、6、Framework、Core 和 Azure。這可確保它符合各種專案需求與環境。

如何取得 C# 文字處理函式庫的試用授權?

若要取得 IronWord 的試用授權,請造訪 Iron Software 網站,並提供您的電子郵件地址。您將透過電子郵件收到一個試用授權金鑰,您可以將此金鑰新增至您的 appsettings.json 檔案。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。