C# 替换Word文档内容成功,但造成文档格式丢失!
做一个批量替换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); //格式化 doc.Content.AutoFormat(); //清空Range对象 Microsoft.Office.Interop.Word.Range range = null; //关闭 doc.Close(ref nullobj, ref nullobj, ref nullobj); //关闭应用 app.Quit(ref nullobj, ref nullobj, ref nullobj); }
/***-------------------------------------------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); }