[英]Word count using Microsoft.Office.Interop.Word
如何使用Microsoft.Office.Interop.Word
Word文档中特定单词的出现次数?
例如,在我的Word文档中,我在不同的位置有两个##<Test Sub Clause1>##
标记。 我需要一个特定文档中它的总数。 在我的示例中,该值为2。
Microsoft.Office.Interop.Word
是否存在任何预定义函数来获取此计数? 或最简单的方法是什么?
您可以尝试一下,这些内容是根据我在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();
}
}
如果要计算单词## <Test Sub Clause1> ##的出现。 那你应该试试这个...
//AddLibrary
using Word = Microsoft.Office.Interop.Word;
并尝试此代码。
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++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.