asp.net操作Word实现批量替换
首先引入Microsoft.Office.Interop.Word组件,该组件在安装完office后在COM中出现。
代码如下
usingSystem; usingSystem.Collections.Generic; usingSystem.Diagnostics; usingSystem.Linq; usingSystem.Text; namespaceTextReplace { publicclassWordOperate:IDisposable { privateMicrosoft.Office.Interop.Word._Application_app; privateMicrosoft.Office.Interop.Word._Document_doc; object_nullobj=System.Reflection.Missing.Value; ///<summary> ///关闭Word进程 ///</summary> publicvoidKillWinword() { varp=Process.GetProcessesByName("WINWORD"); if(p.Any())p[0].Kill(); } ///<summary> ///打开word文档 ///</summary> ///<paramname="filePath"></param> publicvoidOpen(stringfilePath) { _app=newMicrosoft.Office.Interop.Word.ApplicationClass(); objectfile=filePath; _doc=_app.Documents.Open( reffile,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); } ///<summary> ///替换word中的文字 ///</summary> ///<paramname="strOld">查找的文字</param> ///<paramname="strNew">替换的文字</param> publicvoidReplace(stringstrOld,stringstrNew) { _app.Selection.Find.ClearFormatting(); _app.Selection.Find.Replacement.ClearFormatting(); _app.Selection.Find.Text=strOld; _app.Selection.Find.Replacement.Text=strNew; objectobjReplace=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,refobjReplace,ref_nullobj, ref_nullobj,ref_nullobj,ref_nullobj); } ///<summary> ///保存 ///</summary> publicvoidSave() { _doc.Save(); } ///<summary> ///退出 ///</summary> publicvoidDispose() { _doc.Close(ref_nullobj,ref_nullobj,ref_nullobj); _app.Quit(ref_nullobj,ref_nullobj,ref_nullobj); } } }
以上就是关于asp.net如何操作Word实现批量替换的全部代码,希望对大家的学习有所帮助。