【IT168 技术文档】在word应用程序中搜索和替换文本是举手之劳的事情,通过word的对象模型,我们也可以使用编程方式来实现。
Word的对象模型有比较详细的帮助文档,放在 Office 安装程序目录,office 2003是在Program Files\Microsoft Office\OFFICE11\2052下,文档本身是为VBA提供的,在这个目录下还可以看到所有的office应用程序的VBA帮助。
打开VBAWD10.CHM,看到word的对象模型,根据以往的使用经验,很容易在Document对象下找到Content属性,该属性会返回一个文 档文字部分的Range对象,从这个对象中不难取到所有的文档内容,再用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);
}
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);
}
不过,这种做法是很勉强的,对小文档来说,不存在问题,对超长超大的文档来说,这样的实现方法已经暗埋bug了,而且是程序级的bug,因为正常的测试会很难发现问题,在使用中导致程序出现什么样的结果也很难量化描述。