Word count using Microsoft.Office.Interop.Word

不羁岁月 提交于 2019-12-13 21:24:36

问题


How can I get the count of occurrences of a particular word in a Word document using Microsoft.Office.Interop.Word?

For example, in my Word document I have two ##<Test Sub Clause1>## tags in different places. I need a total count of its occurrence in a particular document. In my example, it will be 2.

Is there is any predefined function that exists in Microsoft.Office.Interop.Word to get this count? Or what is the easiest way to accomplish this?


回答1:


Here's something you can try, modified from a code snippet I found at 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();
    }
}

There's also some documentation on MSDN you might want to check out.




回答2:


If you want to count the occurrence of word ##< Test Sub Clause1>##. Then you should try this...

//AddLibrary
using Word = Microsoft.Office.Interop.Word;

And try this Code.

object oMissing = System.Type.Missing;
object outputFile = "C:\\WordCountTest.doc";
Word.Application wordApp = new Word.Application();
Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref outputFile, ref oMissing,
             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
             ref oMissing, ref oMissing, ref oMissing, ref oMissing);
        doc.Activate();
int wordCount = 0;
for (int k = 1; k <= doc.Words.Count; k++)
{
     if (doc.Words[k].Text.TrimEnd() == "Test" && doc.Words[k + 1].Text.TrimEnd() == "Sub" && doc.Words[k + 2].Text.TrimEnd() == "Clause1")
         wordCount++;
}


来源:https://stackoverflow.com/questions/16918066/word-count-using-microsoft-office-interop-word

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!