使用IRONWORD

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

发布 2024年二月22日
分享:

Microsoft Word 文档通常包含丰富的格式,如字体、样式和各种元素,使文档具有视觉吸引力。IronWord 是一款功能强大的程序库,由 铁软件 它拥有直观的 C# 和 VB.NET Word 和 Docx 文档 API。用户无需安装 Microsoft Office 或 Word Interop 即可创建、编辑和导出 Word 文档。IronWord 完全支持 .NET 8、7、6、Framework、Core 和 Azure。这意味着该库无需在机器上安装 Word,就能独立读取文件。如果您正在使用 C# 并需要在读取 Word 文档的同时保留其格式,本教程将指导您使用 IronWord 图书馆

如何 (在 C&num 中;) 阅读带格式的 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;
            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-and-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 "和段落对象,并将其添加到加载的 Word 文档中。

许可 (可免费试用)

IronWord.此密钥需要放在 appsettings.json 中。

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

提供电子邮件以获取试用许可证。提交电子邮件 ID 后,密钥将通过电子邮件发送。

如何用 C# 阅读带格式化的 Word 文档:图 8 - 成功提交试用表单

结论

IronWord 提供了一种用 C# 阅读带格式的 Word 文档的便捷方法。您可以根据自己的具体要求和所处理文档的复杂程度来扩展所提供的代码。本教程可作为集成 IronWord 到您用于 Word 文档处理的 C# 应用程序中。

< 前一页
如何在C#中创建不使用Office Interop的Word文档
下一步 >
3个C#的Word库(开发人员更新列表)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 4,816 查看许可证 >