//filePath:word文档的路径;strOld:需要替换的内容;strNew:替换的新内容;
//注意:strOld中的字符数量要与新的strNew中的一一对应
public static void InitWord(string filePath, List<string> strOld, List<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(); if (strOld.Count > 0) { for (int i = 0; i < strOld.Count; i++) { app.Selection.Find.Text = strOld[i]; app.Selection.Find.Replacement.Text = strNew[i]; 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); }
世界上最可怕事情是比我们优秀的人比我们还努力