IRONSOFTWAREHOME
USING IRONWORD

3 个 C# Word 库(开发人员的更新列表)

Curtis Chau
Curtis Chau
Updated: 2026年5月8日

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类加载'样本.docx'输入Word文档。
  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 库:

PM > 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}");
        }
    }
}

上述代码使用IronWord库类的WordDocument构造方法读取Word文档。

输出

如何在C#中读取带格式的Word文档:图7 - 从前述代码生成的控制台输出

解释

  1. 打开Word文档: 使用WordDocument从IronWord加载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}");
        }
    }
}

这里我们在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}");
        }
    }
}

这里我们创建一个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}");
        }
    }
}

这里我们创建新的Paragraph对象并添加样式信息,然后将它们添加到已加载的Word文档中。

许可(提供免费试用)

获取您的 IronWord 免费试用许可证密钥。 这个密钥需要放在appsettings.json中。

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

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

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

结论

IronWord提供了一种便捷的方式,可以使用 C# 读取带有格式的 Word 文档。 根据您的具体需求和您正在处理的文档的复杂性,扩展提供的代码。 本教程旨在为将IronWord集成到您的 C# 应用程序中以进行 Word 文档处理提供一个起点。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

...
阅读更多

相关文章

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户