您的位置:首页 > 编程语言 > C#

C#使用COM搜索本地word文档关键字

2014-04-28 18:00 459 查看
/// <summary>
/// 检索根目录下的子目录及其所有文件,并在datagridview中显示文档名称及路径--递归调用
/// </summary>
/// <param name="rootPath">根目录</param>
/// <param name="strKey">关键字包</param>
private void GetAllFiles(string rootPath,List<string> strKey)
{
DirectoryInfo dir = new DirectoryInfo(rootPath);
string[] dirs = System.IO.Directory.GetDirectories(rootPath);//得到所有子目录
foreach (string di in dirs)
{
GetAllFiles(di,strKey);
}
FileInfo[] files = dir.GetFiles("*.doc"); //查找文件
//遍历每个word文档
foreach (FileInfo fi in files)
{
string filename = fi.Name;
string filePath = fi.FullName;
object filepath = filePath;
filename = SearchDoc.SearchInDoc(filepath, strKey, filename); //调用检索文档关键字的方法,并返回检索出的文档名称
if (filename != "")
{
dtBGMC.Rows.Add(filename, filepath); //datagridview逐行显示检索出来的结果
}
}
}

/// <summary>
/// search in a DOC file(查询DOC文件的内容)
/// </summary>
/// <param name="filepath">文档路径</param>
/// <param name="strKey">要搜索的关键字数组</param>
/// <param name="filename">文档名称</param>
/// <returns></returns>
public static string SearchInDoc(object filepath, List<string> strKey, string filename)
{
string KeyInfilename = "";
object MissingValue = System.Reflection.Missing.Value;//Type.Missing;
try
{
wp = new Microsoft.Office.Interop.Word.ApplicationClass();
wd = wp.Documents.Open(ref filepath, ref MissingValue,
ref readOnly, 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);
Microsoft.Office.Interop.Word.Find wfnd;

if (wd.Paragraphs != null && wd.Paragraphs.Count > 0)
{
int keyscount = 0;
for (int i = 0; i < strKey.Count; i++) //循环关键字数组
{
for (int j = 1; j <= wd.Paragraphs.Count; j++)
{
wfnd = wd.Paragraphs[j].Range.Find;
wfnd.ClearFormatting();
wfnd.Text = strKey[i].ToString();
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))
{
keyscount++;
break;
}
}
}
if (keyscount == strKey.Count)
{
KeyInfilename = filename;
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (wd != null)
{
wd.Close(ref MissingValue, ref MissingValue, ref MissingValue);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wd);
wd = null;
}

if (wp != null)
{
wp.Quit(ref MissingValue, ref MissingValue, ref MissingValue);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wp);
wp = null;
}

GC.Collect();
}
return KeyInfilename;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: