替换word文件内容

/***-------------------------------------------Word-----------------------------------***/
private void WordReplace(string filePath, string strOld, string strNew)
{
///实例化顶级对象
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.ApplicationClass();
object nullobj = System.Reflection.Missing.Value;
object file = filePath;
//实例化Document对象
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open
(
ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj);
//做替换操作
//doc.Content.Text = doc.Content.Text.Replace(strOld, strNew);
app.Selection.Find.ClearFormatting();
app.Selection.Find.Replacement.ClearFormatting();
app.Selection.Find.Text
= strOld;
app.Selection.Find.Replacement.Text
= strNew;

object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
app.Selection.Find.Execute(
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref objReplace, ref nullobj,
ref nullobj, ref nullobj, ref nullobj);

//格式化
//doc.Content.AutoFormat();
//清空Range对象
//Microsoft.Office.Interop.Word.Range range = null;

//保存
doc.Save();
//关闭
doc.Close(ref nullobj, ref nullobj, ref nullobj);
//关闭应用
app.Quit(ref nullobj, ref nullobj, ref nullobj);
}

posted @ 2011-04-20 20:02  KimSky  阅读(310)  评论(0编辑  收藏  举报