【问题标题】:How to search a given word in word file by C# [closed]如何通过C#在word文件中搜索给定的单词[关闭]
【发布时间】:2018-08-10 03:26:55
【问题描述】:

如何检查word文件是否包含给定的单词?

示例: 我想写一个函数:bool IsContain(string word, string filePath)。 如果 filePath 包含 word,该函数将返回 true。否则会返回 false。

这是我使用 Aspose 框架的解决方案。有没有更好的解决方案?

public class FindContentOfWordDoc
{
    public bool FindContent(string filePath, string content)
    {
        var doc = new Document(filePath);

        var findReplaceOptions = new FindReplaceOptions
        {
            ReplacingCallback = new FindCallBack(),
            Direction = FindReplaceDirection.Backward
        };

        var regex = new Regex(content, RegexOptions.IgnoreCase);
        doc.Range.Replace(regex, "", findReplaceOptions);

        return (findReplaceOptions.ReplacingCallback as FindCallBack)?.IsMatch ?? false;
    }

    private class FindCallBack : IReplacingCallback
    {
        public bool IsMatch { get; private set; }
        ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
        {
            IsMatch = true;
            return ReplaceAction.Stop;
        }
    }
}

谢谢!

【问题讨论】:

  • 我尝试使用 Aspose 框架字。有没有更好的解决方案?
  • 你说的是 Microsoft Word 吗?
  • 是的,我说的是 MS Word。
  • 您是否尝试过将整个文件作为字符串读取并从那里检查? AFAIR 通常不会在 word 文档中加密文本。
  • 不,我没试过。

标签: c# .net aspose


【解决方案1】:

使用 VSTO 跟随 sn-p:

if (Application.Selection.Find.Execute(ref findText,
ref missing, ref missing, ref missing, ref missing, ref missing, ref 
missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref 
missing, 
ref missing, ref missing)) 
{ 
   MessageBox.Show("Text found.");
} 
else
{ 
   MessageBox.Show("The text could not be located.");
}

【讨论】:

  • 它不适用于 MS Word
  • 这是真的。为此事道歉。我没有正确理解这个问题。我认为 sn-p 有效!
【解决方案2】:

如果您使用评论中所述的 Aspose 库,则可以通过 IReplacingCallback 接口的自定义实现来实现。

bool IsContain(string word, string filePath)
{
    Document doc = new Document(filePath);

    OccurrencesCounter counter = new OccurrencesCounter();

    doc.Range.Replace(new Regex(word), counter, false);

    return counter.Occurrences > 0;

}


private class OccurrencesCounter : IReplacingCallback
{
    public ReplaceAction Replacing(ReplacingArgs args)
    {
        mOccurrences++;

        return ReplaceAction.Skip;
    }


    public int Occurrences
    {
        get { return mOccurrences; }
    }

    private int mOccurrences;

}

【讨论】:

    猜你喜欢
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2019-01-27
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多