跳至页脚内容
使用 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#开发环境。
  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

也可以使用 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 免费试用许可证密钥。 此密钥需要放置在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 包管理器将 IronWord 添加到您的项目中。使用 WordDocument 类加载 Word 文档以访问其内容。

在 C# 中读取 Word 文档时如何处理异常?

在 C# 中使用 IronWord 读取 Word 文档时,通过在文档处理代码周围实现 try-catch 块来处理异常。这将有助于管理运行时错误并确保应用程序的稳健性。

我可以使用 C# 从 Word 文档中读取表格吗?

可以,您可以在 C# 中使用 IronWord 从 Word 文档中读取表格。通过 WordDocument 类的 Tables 属性访问表格,并根据需要迭代表格数据。

如何在 C# 中修改 Word 文档的文本样式?

通过创建 TextStyle 对象并将其应用于特定的文本运行或段落,在使用 IronWord 的 Word 文档中修改文本样式。这使您可以自定义字体、大小和其他样式属性。

是否可以在 C# 中向 Word 文档添加新内容?

可以,您可以在 C# 中使用 IronWord 向 Word 文档添加新内容。创建 TextRunParagraph 对象,以在保存更改之前向文档添加样式化内容。

如何在 C# 中保存对 Word 文档的修改?

在使用 IronWord 编辑 Word 文档后,通过调用 WordDocument 实例的 Save 方法保存更改。指定文件路径以创建一个包含修改内容的新文档。

在 C# 中处理 Word 文档是否需要安装 Microsoft Office?

不,使用 IronWord 处理 C# 中的 Word 文档无需安装 Microsoft Office。该库独立于 Microsoft Office 运行,允许您直接处理 Word 文件。

哪些 .NET 版本与 Word 处理库兼容?

IronWord 与许多 .NET 版本兼容,包括 .NET 8、7、6、Framework、Core 和 Azure。这确保它满足各种项目要求和环境。

如何获取 C# 中 Word 处理库的试用许可证?

要获取 IronWord 的试用许可证,请访问 Iron Software 网站并提供您的电子邮件地址。您将通过电子邮件收到试用许可证密钥,可以将其添加到 appsettings.json 文件中。

Jordi Bardia
软件工程师
Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。