站在巨人的肩上

Standing on Shoulders of Giants
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#封装Word常用操作类

Posted on 2010-04-12 21:56  姚箫  阅读(511)  评论(0)    收藏  举报

 

代码
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using Microsoft.Office.Interop.Word;
  5 using System.Diagnostics;
  6 namespace OfficeManager
  7 {
  8     public class WordClass : IDisposable
  9     {
 10         #region 字段
 11         private _Application m_WordApp = null;
 12         private _Document m_Document = null;
 13         private object missing = System.Reflection.Missing.Value;
 14         #endregion
 15         #region 构造函数与析构函数
 16         public WordClass()
 17         {
 18             m_WordApp = new ApplicationClass();
 19         }
 20         ~WordClass()
 21         {
 22             try
 23             {
 24                 if (m_WordApp != null)
 25                     m_WordApp.Quit(ref missing, ref missing, ref missing);
 26             }
 27             catch (Exception ex)
 28             {
 29                 Debug.Write(ex.ToString());
 30             }
 31         }
 32         #endregion
 33         #region 属性
 34         public _Document Document
 35         {
 36             get
 37             {
 38                 return m_Document;
 39             }
 40         }
 41         public _Application WordApplication
 42         {
 43             get
 44             {
 45                 return m_WordApp;
 46             }
 47         }
 48         public int WordCount
 49         {
 50             get
 51             {
 52                 if (m_Document != null)
 53                 {
 54                     Range rng = m_Document.Content;
 55                     rng.Select();
 56                     return m_Document.Characters.Count;
 57                 }
 58                 else
 59                     return -1;
 60             }
 61         }
 62         public object Missing
 63         {
 64             get
 65             {
 66                 return missing;
 67             }
 68         }
 69         #endregion
 70         #region 基本任务
 71         #region CreateDocument
 72         public void CreateDocument(string template)
 73         {
 74             object obj_template = template;
 75             if (template.Length <= 0) obj_template = missing;
 76             m_Document = m_WordApp.Documents.Add(ref obj_template, ref missing, ref missing, ref missing);
 77         }
 78         public void CreateDocument()
 79         {
 80             this.CreateDocument("");
 81         }
 82         #endregion
 83         #region OpenDocument
 84         public void OpenDocument(string fileName, bool readOnly)
 85         {
 86             object obj_FileName = fileName;
 87             object obj_ReadOnly = readOnly;
 88             m_Document = m_WordApp.Documents.Open(ref obj_FileName, ref missing, ref obj_ReadOnly, ref missing,
 89                 ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
 90                 ref missing, ref missing, ref missing, ref missing);
 91         }
 92         public void OpenDocument(string fileName)
 93         {
 94             this.OpenDocument(fileName, false);
 95         }
 96         #endregion
 97         #region Save & SaveAs
 98         public void Save()
 99         {
100             if (m_Document != null)
101                 m_Document.Save();
102         }
103         public void SaveAs(string fileName)
104         {
105             object obj_FileName = fileName;
106             if (m_Document != null)
107             {
108                 m_Document.SaveAs(ref obj_FileName, ref missing, ref missing, ref missing, ref missing,
109                     ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
110                     ref missing, ref missing, ref missing, ref missing);
111             }
112         }
113         #endregion
114         #region Close
115         public void Close(bool isSaveChanges)
116         {
117             object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
118             if (isSaveChanges)
119                 saveChanges = WdSaveOptions.wdSaveChanges;
120             if (m_Document != null)
121                 m_Document.Close(ref saveChanges, ref missing, ref missing);
122         }
123         #endregion
124         #region 添加数据
125         /// <summary>
126         /// 添加图片
127         /// </summary>
128         /// <param name="picName"></param>
129         public void AddPicture(string picName)
130         {
131             if (m_WordApp != null)
132                 m_WordApp.Selection.InlineShapes.AddPicture(picName, ref missing, ref missing, ref missing);
133         }
134         /// <summary>
135         /// 插入页眉
136         /// </summary>
137         /// <param name="text"></param>
138         /// <param name="align"></param>
139         public void SetHeader(string text, WdParagraphAlignment align)
140         {
141             this.m_WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
142             this.m_WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
143             this.m_WordApp.ActiveWindow.ActivePane.Selection.InsertAfter(text); //插入文本
144             this.m_WordApp.Selection.ParagraphFormat.Alignment = align;  //设置对齐方式
145             this.m_WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; // 跳出页眉设置
146         }
147         /// <summary>
148         /// 插入页脚
149         /// </summary>
150         /// <param name="text"></param>
151         /// <param name="align"></param>
152         public void SetFooter(string text, WdParagraphAlignment align)
153         {
154             this.m_WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
155             this.m_WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryFooter;
156             this.m_WordApp.ActiveWindow.ActivePane.Selection.InsertAfter(text); //插入文本
157             this.m_WordApp.Selection.ParagraphFormat.Alignment = align;  //设置对齐方式
158             this.m_WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; // 跳出页眉设置
159         }
160         #endregion
161         #region Print
162         public void PrintOut()
163         {
164             object copies = "1";
165             object pages = "";
166             object range = WdPrintOutRange.wdPrintAllDocument;
167             object items = WdPrintOutItem.wdPrintDocumentContent;
168             object pageType = WdPrintOutPages.wdPrintAllPages;
169             object oTrue = true;
170             object oFalse = false;
171             this.m_Document.PrintOut(
172                 ref oTrue, ref oFalse, ref range, ref missing, ref missing, ref missing,
173                 ref items, ref copies, ref pages, ref pageType, ref oFalse, ref oTrue,
174                 ref missing, ref oFalse, ref missing, ref missing, ref missing, ref missing);
175         }
176         public void PrintPreview()
177         {
178             if (m_Document != null)
179                 m_Document.PrintPreview();
180         }
181         #endregion
182         public void Paste()
183         {
184             try
185             {
186                 if (m_Document != null)
187                 {
188                     m_Document.ActiveWindow.Selection.Paste();
189                 }
190             }
191             catch (Exception ex)
192             {
193                 Debug.Write(ex.Message);
194             }
195         }
196         #endregion
197         #region 文档中的文本和对象
198         public void AppendText(string text)
199         {
200             Selection currentSelection = this.m_WordApp.Selection;
201             // Store the user's current Overtype selection
202             bool userOvertype = this.m_WordApp.Options.Overtype;
203             // Make sure Overtype is turned off.
204             if (this.m_WordApp.Options.Overtype)
205             {
206                 this.m_WordApp.Options.Overtype = false;
207             }
208             // Test to see if selection is an insertion point.
209             if (currentSelection.Type == WdSelectionType.wdSelectionIP)
210             {
211                 currentSelection.TypeText(text);
212                 currentSelection.TypeParagraph();
213             }
214             else
215                 if (currentSelection.Type == WdSelectionType.wdSelectionNormal)
216                 {
217                     // Move to start of selection.
218                     if (this.m_WordApp.Options.ReplaceSelection)
219                     {
220                         object direction = WdCollapseDirection.wdCollapseStart;
221                         currentSelection.Collapse(ref direction);
222                     }
223                     currentSelection.TypeText(text);
224                     currentSelection.TypeParagraph();
225                 }
226                 else
227                 {
228                     // Do nothing.
229                 }
230             // Restore the user's Overtype selection
231             this.m_WordApp.Options.Overtype = userOvertype;
232         }
233         #endregion
234         #region 搜索和替换文档中的文本
235         public void Replace(string oriText, string replaceText)
236         {
237             object replaceAll = WdReplace.wdReplaceAll;
238             this.m_WordApp.Selection.Find.ClearFormatting();
239             this.m_WordApp.Selection.Find.Text = oriText;
240             this.m_WordApp.Selection.Find.Replacement.ClearFormatting();
241             this.m_WordApp.Selection.Find.Replacement.Text = replaceText;
242             this.m_WordApp.Selection.Find.Execute(
243                 ref missing, ref missing, ref missing, ref missing, ref missing,
244                 ref missing, ref missing, ref missing, ref missing, ref missing,
245                 ref replaceAll, ref missing, ref missing, ref missing, ref missing);
246         }
247 
248         #endregion
249         #region 文档中的Word表格
250         /// <summary>
251         /// 向文档中插入表格
252         /// </summary>
253         /// <param name="startIndex">开始位置</param>
254         /// <param name="endIndex">结束位置</param>
255         /// <param name="rowCount">行数</param>
256         /// <param name="columnCount">列数</param>
257         /// <returns></returns>
258         public Table AppendTable(int startIndex, int endIndex, int rowCount, int columnCount)
259         {
260             object start = startIndex;
261             object end = endIndex;
262             Range tableLocation = this.m_Document.Range(ref start, ref end);
263             return this.m_Document.Tables.Add(tableLocation, rowCount, columnCount, ref missing, ref missing);
264         }
265         /// <summary>
266         /// 添加行
267         /// </summary>
268         /// <param name="table"></param>
269         /// <returns></returns>
270         public Row AppendRow(Table table)
271         {
272             object row = table.Rows[1];
273             return table.Rows.Add(ref row);
274         }
275         /// <summary>
276         /// 添加列
277         /// </summary>
278         /// <param name="table"></param>
279         /// <returns></returns>
280         public Column AppendColumn(Table table)
281         {
282             object column = table.Columns[1];
283             return table.Columns.Add(ref column);
284         }
285         /// <summary>
286         /// 设置单元格的文本和对齐方式
287         /// </summary>
288         /// <param name="cell">单元格</param>
289         /// <param name="text">文本</param>
290         /// <param name="align">对齐方式</param>
291         public void SetCellText(Cell cell, string text, WdParagraphAlignment align)
292         {
293             cell.Range.Text = text;
294             cell.Range.ParagraphFormat.Alignment = align;
295         }
296         #endregion
297         #region IDisposable 成员
298         public void Dispose()
299         {
300             try
301             {
302                 if (m_WordApp != null)
303                     m_WordApp.Quit(ref missing, ref missing, ref missing);
304             }
305             catch (Exception ex)
306             {
307                 Debug.Write(ex.ToString());
308             }
309         }
310         #endregion
311     }
312 }