读书人

C#操纵word2007的怪有关问题

发布时间: 2011-12-14 23:20:17 作者: rapoo

C#操纵word2007的怪问题
最近写一个使用C#操纵word的代码,要求使用word中的查找和替换功能,源码如下:


class WdDocument : Microsoft.Office.Interop.Word.ApplicationClass
{
object oSpath;
object oTpath;
object missing = Missing.Value;
public WdDocument(string spath,string opath)
{
this.oSpath = spath;
this.oTpath = opath;

}

public void replacement(string replace, string value)
{
object rWords = replace;
object vWords = value;
object repType = WdReplace.wdReplaceAll;
Document myDoc = this.Documents.Open(ref this.oSpath, 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, ref missing);

myDoc.Select();
Selection.Find.ClearFormatting();
Selection.Find.Text = replace;
Selection.Find.Replacement.ClearFormatting();
Selection.Find.Replacement.Text = value;

Selection.Find.Execute(ref rWords,
ref missing,
ref missing,
ref missing,


ref missing,
ref missing,
ref missing,
ref missing,
ref missing,
ref vWords,
ref repType,


ref missing,
ref missing,
ref missing,
ref missing);

myDoc.SaveAs(ref this.oTpath,
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, ref missing);



myDoc.Close(ref missing, ref missing, ref missing);

this.Quit(ref missing, ref missing, ref missing);
}
}

该代码在Word2003环境中编译运行没有任何问题,但装了word2007之后就没法运行了,总是在

Selection.Find.Text = replace;

抛出异常:
External component has thrown an exception.
注掉该句,直接用
Selection.Find.Execute(……)又抛出参数传递不正确的异常,怀疑是不是2007改啥东西了,有什么别的方法吗?有那位大师遇到过这个问题,帮小弟一把,多谢了!!!

[解决办法]
没用过word2007,想必是有相应的改变,以前word2000和xp的时候也有一些修改,根据版本进行相应的调用

读书人网 >C#

热点推荐