当前位置:文档之家› C#修改word文档的内容

C#修改word文档的内容

C#修改word文档的内容
C#修改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;

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) as Microsoft.Office.Interop.Word._Document;

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();

//Microsoft.Office.Interop.Word.Range range = null;

doc.Close(ref nullobj, ref nullobj, ref nullobj);

app.Quit(ref nullobj, ref nullobj, ref nullobj);

}

相关主题
文本预览
相关文档 最新文档