##使用fileformat.words在Word文檔中替換文本。使用此免費和開源.NET API來執行搜索並以編程方式替換文本。 {.wp-block頭}

如何使用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上找到。因此,社區的貢獻非常感謝。

問一個問題

您可以在論壇上讓我們知道您的問題或查詢。

##常見問題 - 常見問題{.wp-block-neading} **如何使用c#?**找到和替換單詞 使用開源.NET API在Word文檔中執行搜索和替換Word文檔中非常容易。有一些方法可以編程創建和編輯表。 我如何在單詞中找到並替換在表中? 請訪問此鏈接以找到可以幫助您使用C#替換文字表中的文本的代碼段。

另請參見