使用fileformat.words在Word文档中替换文本。使用此免费和开源.NET API来执行搜索并以编程方式替换文本。

如何使用C#执行MS Word表中的查找和替换

概述

在最近的博客文章中,我们讨论了如何使用fileformat.words api打开Word文档。本文将介绍如何使用C#在MS Word表中进行查找和替换。在进行前进之前,请访问我们的博客文章,您将在其中发现如何使用fileformat.words在Word文件中编程表创建表。因此,在单词表中替换单词是一个非常普遍的任务,有时在大数据表的情况下它会耗时。但是,此开源.NET库将帮助您使搜索和更换单词表成为轻量级的过程。因此,请彻底详细介绍本指南,以确保您已经完全了解了这一过程。 我们将在本指南中介绍以下主题:

在Word文件中替换一个单词 - API安装

此开源文字处理API的安装过程相对简单。但是,您可以通过下载Nuget软件包或在Nuget软件包管理器中运行以下命令来安装fileformat.words。

Install-Package FileFormat.Words

如何以编程方式替换Word文档中的文本?

现在,我们可以开始编写代码以编程性能在MS Word表中进行替换。 您可以按照以下提到的步骤和代码段:

  • 初始化文档类的对象并加载DOCX/DOCS文件。
  • 实例化身体类的实例。
  • 创建类的对象。
  • 调用FindTableByText方法,以找到给定文本的表格数量。
  • 调用Findtablerow方法,以查找特定行以及单元格的数量。
  • 调用FindtableCell方法,以查找特定行以及单元格的数量。
  • 通过调用ChangeteXtincell方法,搜索并替换Word文档中的文本。
using FileFormat.Words;
using FileFormat.Words.Table;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = "/Docs.docx";
            // Initialize an object of the Document class and load the Docx/Docs file. 
            using (Document doc1 = new Document(path))
            {
                // Instantiate an instance of the Body class.
                Body body1 = new Body(doc1);
                // Create an object of the Table class. 
                Table table = new Table();
                // Invoke the FindTableByText method to find the number of occurrences of tables for the given text. 
                int tableCount = body1.FindTableByText("British");
                Console.WriteLine("number of tables with this text = " + tableCount);
                // Call the FindTableRow method to find a particular row along with the number of cells. 
                foreach (TableRow row in body1.FindTableRow(0, 1))
                {
                    Console.WriteLine(row.NumberOfCell);
                }
                // Call the FindTableRow method to find a particular row along with the number of cells. 
                foreach (TableCell cell in body1.FindTableCell(0, 1, 1))
                {
                    Console.WriteLine(cell.Text);
                    Console.WriteLine(cell.CellWidth);
                }
                // Search and replace text in Word document by calling the ChangeTextInCell method.
                Console.WriteLine(table.ChangeTextInCell(path, 0, 1, 2, "changed"));
            }

        }

    }
}

将上述代码复制并粘贴到主文件中并运行程序。此外,您可以在下图中看到输出:

replace text in word
replace a word in word

结论

这使我们进入了此博客文章的结尾。我们希望您学习如何使用fileformat.words库在MS Word表中进行查找和替换。此外,您还浏览了此开源.NET API提供的方法。此外,还有其他几种替换Word文档中的单词的方法。因此,不要忘记访问文档以了解其他方法和属性。 最后,fileformat.com继续写有关其他主题的博客文章。此外,您可以在我们的社交媒体平台上关注我们,包括FacebookLinkedInTwitter

贡献

由于.NET的FileFormat.Words是一个开源项目,可在Github上找到。因此,社区的贡献非常感谢。

问一个问题

您可以在我们的论坛上让我们知道您的问题或查询。

常见问题 - 常见问题

**如何使用c#?**找到和替换单词 使用开源.NET API在Word文档中执行搜索和替换Word文档中非常容易。有一些方法可以编程创建和编辑表。 我如何在单词中找到并替换在表中? 请访问此链接,以找到可以帮助您使用C#替换单词表中的文本的代码段。

另请参见