C# 操作Word批量替换

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Diagnostics;
 4 using System.Linq;
 5 using System.Text;
 6 
 7 namespace TextReplace
 8 {
 9     public class WordOperate : IDisposable
10     {
11         private Microsoft.Office.Interop.Word._Application _app;
12         private Microsoft.Office.Interop.Word._Document _doc;
13         object _nullobj = System.Reflection.Missing.Value;
14 
15         /// <summary>
16         /// 关闭Word进程
17         /// </summary>
18         public void KillWinword()
19         {
20             var p = Process.GetProcessesByName("WINWORD");
21             if (p.Any()) p[0].Kill();
22         }
23 
24         /// <summary>
25         /// 打开word文档
26         /// </summary>
27         /// <param name="filePath"></param>
28         public void Open(string filePath)
29         {
30 
31             _app = new Microsoft.Office.Interop.Word.ApplicationClass();
32             object file = filePath;
33             _doc = _app.Documents.Open(
34                  ref file, ref _nullobj, ref _nullobj,
35                  ref _nullobj, ref _nullobj, ref _nullobj,
36                  ref _nullobj, ref _nullobj, ref _nullobj,
37                  ref _nullobj, ref _nullobj, ref _nullobj,
38                  ref _nullobj, ref _nullobj, ref _nullobj, ref _nullobj);
39         }
40 
41 
42         /// <summary>
43         /// 替换word中的文字
44         /// </summary>
45         /// <param name="strOld">查找的文字</param>
46         /// <param name="strNew">替换的文字</param>
47         public void Replace(string strOld, string strNew)
48         {
49             _app.Selection.Find.ClearFormatting();
50             _app.Selection.Find.Replacement.ClearFormatting();
51             _app.Selection.Find.Text = strOld;
52             _app.Selection.Find.Replacement.Text = strNew;
53 
54             object objReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
55             _app.Selection.Find.Execute(ref _nullobj, ref _nullobj, ref _nullobj,
56                                        ref _nullobj, ref _nullobj, ref _nullobj,
57                                        ref _nullobj, ref _nullobj, ref _nullobj,
58                                        ref _nullobj, ref objReplace, ref _nullobj,
59                                        ref _nullobj, ref _nullobj, ref _nullobj);
60         }
61 
62         /// <summary>
63         /// 保存
64         /// </summary>
65         public void Save()
66         {
67             _doc.Save();
68         }
69 
70         /// <summary>
71         /// 退出
72         /// </summary>
73         public void Dispose()
74         {
75             _doc.Close(ref _nullobj, ref _nullobj, ref _nullobj);
76             _app.Quit(ref _nullobj, ref _nullobj, ref _nullobj);
77         }
78     }
79 }

 

posted @ 2013-03-10 13:15  CHANGQING~  阅读(1024)  评论(0编辑  收藏  举报