public static void PrintWordDot(string lv模板文件名, List <string> lv模板词汇, List <string> lv替换词汇) { object path; //文件路径 string strContent; //文件内容 string lvssss = Application.StartupPath + "\\Microsoft.Office.Interop.Word.dll"; Assembly ass; string lv模板文件名含路径 = Application.StartupPath + "\\" + lv模板文件名; Object oMissing = System.Reflection.Missing.Value; object obj模板 = oMissing; object obj; //获取并加载DLL类库中的程序集 ass = Assembly.LoadFile(lvssss); obj = ass.CreateInstance("Microsoft.Office.Interop.Word.ApplicationClass"); //获取类的类型:必须使用名称空间+类名称 Microsoft.Office.Interop.Word._Application WordApp = obj as Microsoft.Office.Interop.Word._Application; WordApp.Visible = true; try { Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Add(ref obj模板, ref oMissing, ref oMissing, ref oMissing); object FindText, ReplaceWith, Replace; for (int lvi = 0; lvi < lv模板词汇.Count; lvi++) { WordDoc.Content.Find.Text = lv模板词汇[lvi]; //要查找的文本 FindText = lv模板词汇[lvi]; //替换文本 //ReplaceWith = strNewText; ReplaceWith = lv替换词汇[lvi]; //wdReplaceAll - 替换找到的所有项。 //wdReplaceNone - 不替换找到的任何项。 //wdReplaceOne - 替换找到的第一项。 Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll; //移除Find的搜索文本和段落格式设置 WordDoc.Content.Find.ClearFormatting(); WordDoc.Content.Find.Execute(ref FindText, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref ReplaceWith, ref Replace, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } WordDoc.PrintPreview(); WordDoc.Saved = true; //关闭wordDoc文档 WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); //关闭wordApp组件对象 WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); } catch //(Exception ex) { WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); throw; } }
/// <summary> /// 文件保存 /// </summary> /// <param name="filename"></param> public void SaveToWord(object filename) { //文件保存 oDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.Close(ref oMissing, ref oMissing, ref oMissing); oWord.Quit(ref oMissing, ref oMissing, ref oMissing); }
private void CloseDoc() { if (_doc != null) { _doc.Close(); _doc = null; } if (_app != null) { _app.Quit(); _app = null; } }