使用Microsoft.Office.Interop.Word计算字数

Nit*_*aul 0 c# interop ms-word

如何使用Microsoft.Office.Interop.Word?获取Word文档中特定单词的出现次数?

例如,在我的Word文档中,我##<Test Sub Clause1>##在不同的地方有两个标签.我需要在特定文档中记录它的总数.在我的例子中,它将是2.

是否存在任何预定义的函数Microsoft.Office.Interop.Word来获取此计数?或者最简单的方法是什么?

Gra*_*ICA 5

这是你可以尝试的东西,我在dotnetperls上找到的代码片段进行了修改.

using System;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main()
    {
        var wordToFind = "some_word_to_find";
        var wordCounter = 0;

        // Open a doc file.
        var application = new Application();
        var document = application.Documents.Open("C:\\word.doc");

        // Loop through all words in the document.
        for (var i = 1; i <= document.Words.Count; i++)
            if (document.Words[i].Text.TrimEnd() == wordToFind)
                wordCounter++;

        Console.WriteLine("Matches Found: {0}", wordCounter);

        // Close word.
        application.Quit();
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能还想查看MSDN上的一些文档.