在C#中搜索Word文档

3

我正在制作一个搜索模块(使用C#的Windows窗体)。它可以很好地处理.txt文件,但是我还需要在Word文档中进行单词搜索。 我尝试使用Microsoft.Office.Interop.Word; 以下是代码:

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document docOpen = app.Documents.Open(flname);
StreamReader srObj = new StreamReader(flname);
string read = srObj.ReadToEnd();
if (read.Contains(txtWordInput.Text)) // searching for the input word in the file
{
      count1++;
      lbSearchList.Visible = true;
      lbSearchList.Items.Add(flname);
}
srObj.Close();
app.Documents.Close();

但在运行时,程序报错“文档文件已经打开,无法进行访问”,即使该文档未被打开。我尝试使用流读取器简单地处理,它可以读取该文件,但读取的数据是一些随机符号,而不是实际写入的内容。因此,if (read.Contains(txtWordInput.Text)) 语句无法搜索单词。
请给出代码示例,说明如何成功搜索 Word 文档中的单词。

通过那段代码看起来错误是正确的。你尝试打开同一个文档两次。首先使用 "app.Documents.Open(flname)" 这一行,然后再创建一个具有相同文件名的 StreamReader 对象。另外,Word 文档不是一个文本文件,而实际上是一个包含其他文件的压缩文件。因此,如果你只是尝试使用流读取器将文件作为文本读取,你会得到你所得到的东西...一堆符号。 - compman2408
3个回答

2

根据该代码,错误是正确的。您尝试两次打开文档。首先使用 "app.Documents.Open(flname)" 行,然后再次通过创建一个具有相同文件名的 StreamReader 对象打开。此外,Word 文档不是纯文本文件,而是包含其他文件的 zip 文件。因此,如果您只尝试使用 StreamReader 以文本形式读取文件,那么您将得到与原始文件一样的一堆符号。

请使用这种方法来简单地读取文本并在 Word 文件中搜索特定字符串。此外,请确保有正确的 using 语句。

using Word = Microsoft.Office.Interop.Word;

public static Boolean CheckWordDocumentForString(String documentLocation, String stringToSearchFor, Boolean caseSensitive = true)
{
    // Create an application object if the passed in object is null
    Word.Application winword = new Word.Application();

    // Use the application object to open our word document in ReadOnly mode
    Word.Document wordDoc = winword.Documents.Open(documentLocation, ReadOnly: true);

    // Search for our string in the document
    Boolean result;
    if (caseSensitive)
        result = wordDoc.Content.Text.IndexOf(stringToSearchFor) >= 0;
    else
        result = wordDoc.Content.Text.IndexOf(stringToSearchFor, StringComparison.CurrentCultureIgnoreCase) >= 0;

    // Close the document and the application since we're done searching
    wordDoc.Close();
    winword.Quit();

    return result;
}

然后要使用这个方法,只需像任何其他静态方法一样调用它。
MyClass.CheckWordDocumentForString(@"C:\Users\CoolDude\Documents\MyWordDoc.docx", "memory", false);

使用您的代码,类似于以下内容:
if (MyClass.CheckWordDocumentForString(flname, txtWordInput.Text, false))
{
    // Do something if it is found
}
else
{
    // Do something if it is not found
}

0

我的建议是,在这种情况下,srObj 是完全无关紧要的,您所做的是绕过并忽略了您的 docOpen 和 app 对象,您创建了它们却从未使用过。我简要查看了 API,发现有一些方法可以获取字符列表和单词集合。我认为您需要做的是从 docOpen 属性中获取单词集合并对它们进行筛选。

您可以使用属性 docOpen.Words 来获取或设置单词集合,或使用 docOpen.Text 获取或设置所有文本内容。

作为示例

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document docOpen = app.Documents.Open(flname);
string read = docOpen.Text
if(read.Contains(txtWordInput.Text)) {
     count1++;
     lbSearchList.Visible = true;
     lbSearchList.Items.Add(flname);
}
app.Documents.Close();

希望这能有所帮助。


嘿,詹姆斯..很抱歉,但是行字符串read = docOpen.Text出现了错误,提示Microsoft.Office.Interop.Word.Document不包含text的定义。 - sam
Kiran Hedge,谢谢你的代码,但它在搜索之前就打开了文档。我有两个文档,其中包含我在嵌套目录中搜索的单词“sam”。它搜索到一个并打开了它,其余的搜索被中断了。我的模块的正确流程是先搜索文档名称并将它们列在列表框中,然后从列表中单击任何路径以打开文件。对于文本文档,它运行良好,但对于Word,每次使用Microsoft.office interop时,它都会打开文档并中断流程。 - sam

0

我认为你可以使用Interop库的Find函数而不是流。 你可以使用以下函数来检查Word文档中是否存在所需文本。

    protected bool FindTextInWord(object text, string flname)
    {
        object matchCase = false;
        object matchWholeWord = true;
        object matchWildCards = false;
        object matchSoundsLike = false;
        object matchAllWordForms = false;
        object forward = true;
        object format = false;
        object matchKashida = false;
        object matchDiacritics = false;
        object matchAlefHamza = false;
        object matchControl = false;
        object read_only = false;
        object visible = true;
        object replace = 2;
        object wrap = 1;

        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document docOpen = app.Documents.Open(flname);
        bool val = false;
        try
        {
            val = app.Selection.Find.Execute(ref text, ref matchCase, ref matchWholeWord,
            ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap,
            ref format, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        }
        finally
        {
            app.Documents.Close();
        }
        return val;
    }

您可以在以下链接中查看每个参数的详细信息 http://msdn.microsoft.com/en-us/library/office/ff193977(v=office.15).aspx

您可以按照以下方式调用函数

FindTextInWord((object)"Proposal","your file name here");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接