如何使用 Aspose.Words 在 C# 中读取 Word 文档

如何使用 Aspose.Words 在 C# 中读取 Word 文档

阅读 Word 文件在 C# 可以简单使用 Aspose.Words 图书馆. 此教程提供详细的指示如何设置您的环境,步骤步骤程序阅读 Word 文件,和可运行代码的例子. 您将学习如何阅读各种格式,如 DOCX 或 DOC,以及如何在 Word 文档中访问不同的元素。

阅读文档的好处

  • 访问文件元素:- 提取和操纵段落,表和文本的运行。

  • 簡單的整合:- 轻松地将 Word 文档阅读集成到您的 C# 应用程序中。

  • 多元性:- 轻松地处理不同的字格式。

原文:《Word Document Reading》

  • 确保您有 Visual Studio 或其他 .NET IDE 安装。
  • 通过 NuGet 包管理器安装 Aspose.Words 图书馆。
  • 计划您的项目结构,以包含教程所需的代码文件。

步骤指南 阅读一个字文档

步骤1:设置环境

在您的 .NET 项目中,使用 NuGet 包管理器添加 Aspose.Words 图书馆。

命令运行:Install-Package Aspose.Words

步骤2:下载DOCX输入文件

创建文档类的例子,并加载DOCX文件。

using Aspose.Words;

Document doc = new Document("input.docx");

步骤3:获取所有段落节点

从文档中删除所有类型段落的节点。

foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
{
    Console.WriteLine(para.ToString(SaveFormat.Text));
}

步骤4:获取所有运行节点

从文档中恢复所有运行类型节点。

foreach (Run run in doc.GetChildNodes(NodeType.Run, true))
{
    Font font = run.Font;
    Console.WriteLine($"{font.Name}, {font.Size}");
    Console.WriteLine(run.Text);
}

示例代码在 C# 中阅读 Word 文件

这里是完整的代码,结合了上述所有步骤。

// Load the source Word file to be read
Document doc = new Document("input.docx");

// Read all paragraphs in the document and display their content
foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
{
    Console.WriteLine(para.ToString(SaveFormat.Text));
}

// Read all Runs in the document and display style and text
foreach (Run run in doc.GetChildNodes(NodeType.Run, true))
{
    Font font = run.Font;
    Console.WriteLine($"{font.Name}, {font.Size}");
    Console.WriteLine(run.Text);
}

结论

在此教程中,您已经学会了如何使用 Aspose.Words 在 C# 中阅读 Word 文档,包括配置和代码示例. 此知识允许您在 Word 文件中访问各种元素,使其更容易处理或显示所需的内容。

 中文