用C#實現(xiàn)在Word文檔中搜索文本

字號:

Word的對象模型有比較詳細的幫助文檔,放在Office安裝程序目錄,office 2003是在Program Files\Microsoft Office\OFFICE11\2052下,文檔本身是為VBA提供的,在這個目錄下還可以看到所有的office應用程序的VBA幫助。
    打開VBAWD10.CHM,看到word的對象模型,根據(jù)以往的使用經(jīng)驗,很容易在Document對象下找到Content屬性,該屬性會返回一個文檔文字部分的Range對象,從這個對象中不難取到所有的文檔內(nèi)容,再用string的IndexOf()方法很容易達到目標。
    object filename=""; //要打開的文檔路徑
    string strKey=""; //要搜索的文本
    object MissingValue=Type.Missing;
    Word.Application wp=new Word.ApplicationClass();
    Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue);
    if (wd.Content.Text.IndexOf(strKey)>=0)
    {
     MessageBox.Show("文檔中包含指定的關鍵字!","搜索結果",MessageBoxButtons.OK);
    }
    else
    {
     MessageBox.Show("文檔中沒有指定的關鍵字!","搜索結果",MessageBoxButtons.OK);
    }
    不過,這種做法是很勉強的,對小文檔來說,不存在問題,對超長超大的文檔來說,這樣的實現(xiàn)方法已經(jīng)暗埋bug了,而且是程序級的bug,因為正常的測試會很難發(fā)現(xiàn)問題,在使用中導致程序出現(xiàn)什么樣的結果也很難量化描述。
    其實,在word中已經(jīng)提供了可以用作搜索的對象Find,在對象模型上也比較容易找到,對應的說明是這樣的:該對象代表查找操作的執(zhí)行條件。Find 對象的屬性和方法與“替換”對話框中的選項一致。從模型上看,F(xiàn)ind對象是Selection的成員,從示例代碼來看似乎也是Range的成員,查找Range的屬性,果然如此。于是修改上面的代碼:
    wd.Content.Find.Text=strKey;
    if (wd.Content.Find.Execute(ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue))
    {
     MessageBox.Show("文檔中包含指定的關鍵字!","搜索結果",MessageBoxButtons.OK);
    }
    else
    {
     MessageBox.Show("文檔中沒有指定的關鍵字!","搜索結果",MessageBoxButtons.OK);
    }
    這樣似乎也不是,因為我只要判斷指定的文本是不是在文檔中,而不需要知道它出現(xiàn)了幾次,如果有多個要搜索的文本,難道每次都進行全文檔搜索?假設我要搜索的文本包含在文檔中,的情況是在文檔開頭就包含我要查找的文本,最壞的情況是在文檔的最后包含要查找的文本,如果每次取一部分文檔進行判斷,符合條件就結束本次搜索,就可以避免每次搜索整個文檔了。模型中的Paragraphs對象現(xiàn)在派上用場了,再修改一下代碼:
    int i=0,iCount=0;
    Word.Find wfnd;
    if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
    {
     iCount=wd.Paragraphs.Count;
     for(i=1;i<=iCount;i++)
     {
     wfnd=wd.Paragraphs[i].Range.Find;
     wfnd.ClearFormatting();
     wfnd.Text=strKey;
     if (wfnd.Execute(ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue,ref MissingValue,
     ref MissingValue))
     {
     MessageBox.Show("文檔中包含指定的