word操作
Code
1using System;
2using System.Collections.Generic;
3using System.Text;
4using Microsoft.Office.Interop.Word;
5using System.IO;
6using System.Web;
7using System.Data;
8using System.Reflection;
9using Microsoft.Win32;
10using System.Text.RegularExpressions;
11using System.Net;
12
13namespace OfficeOperate
14{
15 public class WordOperate
16 {
17 动态生成Word文档并填充数据#region 动态生成Word文档并填充数据
18 /**//// <summary>
19 /// 动态生成Word文档并填充数据
20 /// </summary>
21 /// <returns>返回自定义信息</returns>
22 public static string CreateWordFile()
23 {
24 string message = "";
25 try
26 {
27 Object oMissing = System.Reflection.Missing.Value;
28 string dir = System.Web.HttpContext.Current.Server.MapPath( "" );//首先在类库添加using System.web的引用
29 if( !Directory.Exists( dir + "\\file" ) )
30 {
31 Directory.CreateDirectory( dir + "\\file" ); //创建文件所在目录
32 }
33 string name = DateTime.Now.ToLongDateString() + ".doc";
34 object filename = dir + "\\file\\" + name; //文件保存路径
35 //创建Word文档
36 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
37 Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
38
39 /**/////添加页眉方法一:
40 //WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
41 //WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
42 //WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "无锡全真通科技有限公司" );//页眉内容
43
44 //添加页眉方法二:
45 if( WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView )
46 {
47 WordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
48 }
49 WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
50 string sHeader = "页眉内容";
51 WordApp.Selection.HeaderFooter.LinkToPrevious = false;
52 WordApp.Selection.HeaderFooter.Range.Text = sHeader;
53 WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
54
55
56 //WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
57 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;//设置左对齐
58 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置
59
60 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
61
62 //移动焦点并换行
63 object count = 14;
64 object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
65 WordApp.Selection.MoveDown( ref WdLine, ref count, ref oMissing );//移动焦点
66 WordApp.Selection.TypeParagraph();//插入段落
67
68 //文档中创建表格
69 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add( WordApp.Selection.Range, 12, 3, ref oMissing, ref oMissing );
70 //设置表格样式
71 newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
72 newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
73 newTable.Columns[1].Width = 100f;
74 newTable.Columns[2].Width = 220f;
75 newTable.Columns[3].Width = 105f;
76
77 //填充表格内容
78 newTable.Cell( 1, 1 ).Range.Text = "产品详细信息表";
79 newTable.Cell( 1, 1 ).Range.Bold = 2;//设置单元格中字体为粗体
80 //合并单元格
81 newTable.Cell( 1, 1 ).Merge( newTable.Cell( 1, 3 ) );
82 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
83 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
84
85 //填充表格内容
86 newTable.Cell( 2, 1 ).Range.Text = "产品基本信息";
87 newTable.Cell( 2, 1 ).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
88 //合并单元格
89 newTable.Cell( 2, 1 ).Merge( newTable.Cell( 2, 3 ) );
90 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
91
92 //填充表格内容
93 newTable.Cell( 3, 1 ).Range.Text = "品牌名称:";
94 newTable.Cell( 3, 2 ).Range.Text = "BrandName";
95 //纵向合并单元格
96 newTable.Cell( 3, 3 ).Select();//选中一行
97 object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
98 object moveCount = 5;
99 object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
100 WordApp.Selection.MoveDown( ref moveUnit, ref moveCount, ref moveExtend );
101 WordApp.Selection.Cells.Merge();
102
103 //插入图片
104 if( File.Exists( System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" ) ) )
105 {
106 string FileName = System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" );//图片所在路径
107 object LinkToFile = false;
108 object SaveWithDocument = true;
109 object Anchor = WordDoc.Application.Selection.Range;
110 WordDoc.Application.ActiveDocument.InlineShapes.AddPicture( FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor );
111 WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
112 WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
113 }
114 //将图片设置为四周环绕型
115 Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
116 s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
117
118 newTable.Cell( 12, 1 ).Range.Text = "产品特殊属性";
119 newTable.Cell( 12, 1 ).Merge( newTable.Cell( 12, 3 ) );
120 //在表格中增加行
121 WordDoc.Content.Tables[1].Rows.Add( ref oMissing );
122
123 WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
124 WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
125
126 //文件保存
127 WordDoc.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 );
128 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
129 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
130 message = name + "文档生成成功";
131 }
132 catch
133 {
134 message = "文件导出异常!";
135 }
136 return message;
137 }
138 #endregion
139
140 创建并打开一个空的word文档进行编辑#region 创建并打开一个空的word文档进行编辑
141 /**//// <summary>
142 /// 创建并打开一个空的word文档进行编辑
143 /// </summary>
144 public static void OpenNewWordFileToEdit()
145 {
146 object oMissing = System.Reflection.Missing.Value;
147 Microsoft.Office.Interop.Word.Application WordApp;
148 Microsoft.Office.Interop.Word.Document WordDoc;
149 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
150 WordApp.Visible = true;
151 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
152 }
153 #endregion
154
155 创建word文档#region 创建word文档
156 /**//// <summary>
157 /// 创建word文档
158 /// </summary>
159 /// <returns></returns>
160 public static string createWord()
161 {
162 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
163 Document WordDoc;
164 string strContent = "";
165
166 object strFileName = System.Web.HttpContext.Current.Server.MapPath( "test.doc " );
167 if( System.IO.File.Exists( (string)strFileName ) )
168 System.IO.File.Delete( (string)strFileName );
169 Object oMissing = System.Reflection.Missing.Value;
170 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
171
172 将数据库中读取得数据写入到word文件中#region 将数据库中读取得数据写入到word文件中
173 strContent = "你好\n\n\r ";
174 WordDoc.Paragraphs.Last.Range.Text = strContent;
175 strContent = "这是测试程序 ";
176 WordDoc.Paragraphs.Last.Range.Text = strContent;
177 #endregion
178
179 //将WordDoc文档对象的内容保存为DOC文档
180 WordDoc.SaveAs( ref strFileName, 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 );
181 //关闭WordDoc文档对象
182 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
183 //关闭WordApp组件对象
184 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
185
186 string message = strFileName + "\r\n " + "创建成功 ";
187 return message;
188 }
189 #endregion
190
191 把Word文档装化为Html文件#region 把Word文档装化为Html文件
192 /**//// <summary>
193 /// 把Word文档装化为Html文件
194 /// </summary>
195 /// <param name="strFileName">要转换的Word文档</param>
196 public static void WordToHtml( string strFileName )
197 {
198 string saveFileName = strFileName + DateTime.Now.ToString( "yyyy-MM-dd-HH-mm-ss" ) + ".html";
199 WordToHtml( strFileName, saveFileName );
200 }
201 /**//// <summary>
202 /// 把Word文档装化为Html文件
203 /// </summary>
204 /// <param name="strFileName">要转换的Word文档</param>
205 /// <param name="strSaveFileName">要生成的具体的Html页面</param>
206 public static void WordToHtml( string strFileName, string strSaveFileName )
207 {
208 Microsoft.Office.Interop.Word.ApplicationClass WordApp;
209 Microsoft.Office.Interop.Word.Document WordDoc;
210 Object oMissing = System.Reflection.Missing.Value;
211 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
212 object fileName = strFileName;
213
214 WordDoc = WordApp.Documents.Open( ref fileName,
215 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
216 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
217 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing );
218
219 Type wordType = WordApp.GetType();
220 // 打开文件
221 Type docsType = WordApp.Documents.GetType();
222 // 转换格式,另存为
223 Type docType = WordDoc.GetType();
224 object saveFileName = strSaveFileName;
225 docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML } );
226
227 其它格式:#region 其它格式:
228 /**//**/
229 /**////wdFormatHTML
230 ///wdFormatDocument
231 ///wdFormatDOSText
232 ///wdFormatDOSTextLineBreaks
233 ///wdFormatEncodedText
234 ///wdFormatRTF
235 ///wdFormatTemplate
236 ///wdFormatText
237 ///wdFormatTextLineBreaks
238 ///wdFormatUnicodeText
239 //-----------------------------------------------------------------------------------
240 // docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
241 // null, WordDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
242 // 退出 Word
243 //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
244 // null, WordApp, null );
245 #endregion
246 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
247 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
248 }
249 #endregion
250
251 导入模板#region 导入模板
252 /**//// <summary>
253 /// 导入模板
254 /// </summary>
255 /// <param name="filePath">模板文档路径</param>
256 public static void ImportTemplate( string filePath )
257 {
258 object oMissing = System.Reflection.Missing.Value;
259 Microsoft.Office.Interop.Word.Application WordApp;
260 Microsoft.Office.Interop.Word.Document WordDoc;
261 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
262 WordApp.Visible = true;
263 object fileName = filePath;
264 WordDoc = WordApp.Documents.Add( ref fileName, ref oMissing, ref oMissing, ref oMissing );
265 }
266 #endregion
267
268 word中添加新表#region word中添加新表
269 /**//// <summary>
270 /// word中添加新表
271 /// </summary>
272 public static void AddTable()
273 {
274 object oMissing = System.Reflection.Missing.Value;
275 Microsoft.Office.Interop.Word.Application WordApp;
276 Microsoft.Office.Interop.Word.Document WordDoc;
277 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
278 WordApp.Visible = true;
279 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
280
281 object start = 0;
282 object end = 0;
283 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
284 WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );//3行4列的表
285 }
286 #endregion
287
288 在表中插入新行#region 在表中插入新行
289 /**//// <summary>
290 /// 在表中插入新的1行
291 /// </summary>
292 public static void AddRow()
293 {
294 object oMissing = System.Reflection.Missing.Value;
295 Microsoft.Office.Interop.Word.Application WordApp;
296 Microsoft.Office.Interop.Word.Document WordDoc;
297 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
298 WordApp.Visible = true;
299 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
300
301 object start = 0;
302 object end = 0;
303 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
304 WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
305
306 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
307 object beforeRow = newTable.Rows[1];
308 newTable.Rows.Add( ref beforeRow );
309 }
310 #endregion
311
312 分离单元格#region 分离单元格
313 /**//// <summary>
314 /// 合并单元格
315 /// </summary>
316 public static void CombinationCell()
317 {
318 object oMissing = System.Reflection.Missing.Value;
319 Microsoft.Office.Interop.Word.Application WordApp;
320 Microsoft.Office.Interop.Word.Document WordDoc;
321 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
322 WordApp.Visible = true;
323 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
324
325 object start = 0;
326 object end = 0;
327 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
328 WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
329
330 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
331 object beforeRow = newTable.Rows[1];
332 newTable.Rows.Add( ref beforeRow );
333
334 Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 2, 1 );//2行1列合并2行2列为一起
335 cell.Merge( newTable.Cell( 2, 2 ) );
336 //cell.Merge( newTable.Cell( 1, 3 ) );
337 }
338 #endregion
339
340 分离单元格#region 分离单元格
341 /**//// <summary>
342 /// 分离单元格
343 /// </summary>
344 public static void SeparateCell()
345 {
346 object oMissing = System.Reflection.Missing.Value;
347 Microsoft.Office.Interop.Word.Application WordApp;
348 Microsoft.Office.Interop.Word.Document WordDoc;
349 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
350 WordApp.Visible = true;
351 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
352
353 object start = 0;
354 object end = 0;
355 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
356 WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
357
358 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
359 object beforeRow = newTable.Rows[1];
360 newTable.Rows.Add( ref beforeRow );
361
362 Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 1, 1 );
363 cell.Merge( newTable.Cell( 1, 2 ) );
364
365 object Rownum = 2;
366 object Columnnum = 2;
367 cell.Split( ref Rownum, ref Columnnum );
368 }
369 #endregion
370
371 通过段落控制插入Insert a paragraph at the beginning of the document.#region 通过段落控制插入Insert a paragraph at the beginning of the document.
372 /**//// <summary>
373 /// 通过段落控制插入Insert a paragraph at the beginning of the document.
374 /// </summary>
375 public static void Insert()
376 {
377 object oMissing = System.Reflection.Missing.Value;
378 //object oEndOfDoc = "\\endofdoc"; /**//* \endofdoc is a predefined bookmark */
379
380 //Start Word and create a new document.
381 Microsoft.Office.Interop.Word.Application WordApp;
382 Microsoft.Office.Interop.Word.Document WordDoc;
383 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
384 WordApp.Visible = true;
385
386 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
387
388 //Insert a paragraph at the beginning of the document.
389 Microsoft.Office.Interop.Word.Paragraph oPara1;
390 oPara1 = WordDoc.Content.Paragraphs.Add( ref oMissing );
391 oPara1.Range.Text = "Heading 1";
392 oPara1.Range.Font.Bold = 1;
393 oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
394 oPara1.Range.InsertParagraphAfter();
395 }
396 #endregion
397
398 word文档设置及获取光标位置#region word文档设置及获取光标位置
399 /**//// <summary>
400 /// word文档设置及获取光标位置
401 /// </summary>
402 public static void WordSet()
403 {
404 object oMissing = System.Reflection.Missing.Value;
405 Microsoft.Office.Interop.Word.Application WordApp;
406 Microsoft.Office.Interop.Word.Document WordDoc;
407 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
408
409 文档格式设置#region 文档格式设置
410 WordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0;//行编号
411 WordApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//页面方向
412 WordApp.ActiveDocument.PageSetup.TopMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//上页边距
413 WordApp.ActiveDocument.PageSetup.BottomMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//下页边距
414 WordApp.ActiveDocument.PageSetup.LeftMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//左页边距
415 WordApp.ActiveDocument.PageSetup.RightMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//右页边距
416 WordApp.ActiveDocument.PageSetup.Gutter = WordApp.CentimetersToPoints( float.Parse( "0" ) );//装订线位置
417 WordApp.ActiveDocument.PageSetup.HeaderDistance = WordApp.CentimetersToPoints( float.Parse( "1.5" ) );//页眉
418 WordApp.ActiveDocument.PageSetup.FooterDistance = WordApp.CentimetersToPoints( float.Parse( "1.75" ) );//页脚
419 WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints( float.Parse( "21" ) );//纸张宽度
420 WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints( float.Parse( "29.7" ) );//纸张高度
421 WordApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
422 WordApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
423 WordApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//节的起始位置:新建页
424 WordApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//页眉页脚-奇偶页不同
425 WordApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//页眉页脚-首页不同
426 WordApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//页面垂直对齐方式
427 WordApp.ActiveDocument.PageSetup.SuppressEndnotes = 0;//不隐藏尾注
428 WordApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不设置首页的内外边距
429 WordApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不双面打印
430 WordApp.ActiveDocument.PageSetup.BookFoldPrinting = false;//不设置手动双面正面打印
431 WordApp.ActiveDocument.PageSetup.BookFoldRevPrinting = false;//不设置手动双面背面打印
432 WordApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默认份数
433 WordApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//装订线位于左侧
434 WordApp.ActiveDocument.PageSetup.LinesPage = 40;//默认页行数量
435 WordApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式为“只指定行网格”
436 #endregion
437
438 段落格式设定#region 段落格式设定
439 WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//左缩进
440 WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//右缩进
441 WordApp.Selection.ParagraphFormat.SpaceBefore = float.Parse( "0" );//段前间距
442 WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;//
443 WordApp.Selection.ParagraphFormat.SpaceAfter = float.Parse( "0" );//段后间距
444 WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;//
445 WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//单倍行距
446 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端对齐
447 WordApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制
448 WordApp.Selection.ParagraphFormat.KeepWithNext = 0;//与下段同页
449 WordApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分页
450 WordApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分页
451 WordApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行号
452 WordApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字
453 WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//首行缩进
454 WordApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText;
455 WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse( "0" );
456 WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse( "0" );
457 WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse( "0" );
458 WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse( "0" );
459 WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse( "0" );
460 WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1;
461 WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = 0;
462 WordApp.Selection.ParagraphFormat.FarEastLineBreakControl = 1;
463 WordApp.Selection.ParagraphFormat.WordWrap = 1;
464 WordApp.Selection.ParagraphFormat.HangingPunctuation = 1;
465 WordApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0;
466 WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1;
467 WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1;
468 WordApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto;
469 #endregion
470
471 字体格式设定#region 字体格式设定
472 WordApp.Selection.Font.NameFarEast = "华文中宋";
473 WordApp.Selection.Font.NameAscii = "Times New Roman";
474 WordApp.Selection.Font.NameOther = "Times New Roman";
475 WordApp.Selection.Font.Name = "宋体";
476 WordApp.Selection.Font.Size = float.Parse( "14" );
477 WordApp.Selection.Font.Bold = 0;
478 WordApp.Selection.Font.Italic = 0;
479 WordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
480 WordApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
481 WordApp.Selection.Font.StrikeThrough = 0;//删除线
482 WordApp.Selection.Font.DoubleStrikeThrough = 0;//双删除线
483 WordApp.Selection.Font.Outline = 0;//空心
484 WordApp.Selection.Font.Emboss = 0;//阳文
485 WordApp.Selection.Font.Shadow = 0;//阴影
486 WordApp.Selection.Font.Hidden = 0;//隐藏文字
487 WordApp.Selection.Font.SmallCaps = 0;//小型大写字母
488 WordApp.Selection.Font.AllCaps = 0;//全部大写字母
489 WordApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
490 WordApp.Selection.Font.Engrave = 0;//阴文
491 WordApp.Selection.Font.Superscript = 0;//上标
492 WordApp.Selection.Font.Subscript = 0;//下标
493 WordApp.Selection.Font.Spacing = float.Parse( "0" );//字符间距
494 WordApp.Selection.Font.Scaling = 100;//字符缩放
495 WordApp.Selection.Font.Position = 0;//位置
496 WordApp.Selection.Font.Kerning = float.Parse( "1" );//字体间距调整
497 WordApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果
498 WordApp.Selection.Font.DisableCharacterSpaceGrid = false;
499 WordApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone;
500
501 #endregion
502
503 获取光标位置#region 获取光标位置
504 /**/////get_Information
505 WordApp.Selection.get_Information( WdInformation.wdActiveEndPageNumber );
506 //关于行号-页号-列号-位置
507 //information 属性
508 //返回有关指定的所选内容或区域的信息。variant 类型,只读。
509 //expression.information(type)
510 //expression 必需。该表达式返回一个 range 或 selection 对象。
511 //type long 类型,必需。需要返回的信息。可取下列 wdinformation 常量之一:
512 //wdactiveendadjustedpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾。如果设置了一个起始页码,并对页码进行了手工调整,则返回调整过的页码。
513 //wdactiveendpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾,页码从文档的开头开始计算而不考虑对页码的任何手工调整。
514 //wdactiveendsectionnumber 返回节号,在该节中包含了指定的所选内容或区域的活动结尾。
515 //wdatendofrowmarker 如果指定的所选内容或区域位于表格的行结尾标记处,则本参数返回 true。
516 //wdcapslock 如果大写字母锁定模式有效,则本参数返回 true。
517 //wdendofrangecolumnnumber 返回表格列号,在该表格列中包含了指定的所选内容或区域的活动结尾。
518 //wdendofrangerownumber 返回表格行号,在该表格行包含了指定的所选内容或区域的活动结尾。
519 //wdfirstcharactercolumnnumber 返回指定的所选内容或区域中第一个字符的位置。如果所选内容或区域是折叠的,则返回所选内容或区域右侧紧接着的字符编号。
520 //wdfirstcharacterlinenumber 返回所选内容中第一个字符的行号。如果 pagination 属性为 false,或 draft 属性为 true,则返回 - 1。
521 //wdframeisselected 如果所选内容或区域是一个完整的图文框文本框,则本参数返回 true。
522 //wdheaderfootertype 返回一个值,该值表明包含了指定的所选内容或区域的页眉或页脚的类型,如下表所示。 值 页眉或页脚的类型
523 //- 1 无
524 //0 偶数页页眉
525 //1 奇数页页眉
526 //2 偶数页页脚
527 //3 奇数页页脚
528 //4 第一个页眉
529 //5 第一个页脚
530 //wdhorizontalpositionrelativetopage 返回指定的所选内容或区域的水平位置。该位置是所选内容或区域的左边与页面的左边之间的距离,以磅为单位。如果所选内容或区域不可见,则返回 - 1。
531 //wdhorizontalpositionrelativetotextboundary 返回指定的所选内容或区域相对于周围最近的正文边界的左边的水平位置,以磅为单位。如果所选内容或区域没有显示在当前屏幕,则本参数返回 - 1。
532 //wdinclipboard 有关此常量的详细内容,请参阅 microsoft office 98 macintosh 版的语言参考帮助。
533 //wdincommentpane 如果指定的所选内容或区域位于批注窗格,则返回 true。
534 //wdinendnote 如果指定的所选内容或区域位于页面视图的尾注区内,或者位于普通视图的尾注窗格中,则本参数返回 true。
535 //wdinfootnote 如果指定的所选内容或区域位于页面视图的脚注区内,或者位于普通视图的脚注窗格中,则本参数返回 true。
536 //wdinfootnoteendnotepane 如果指定的所选内容或区域位于页面视图的脚注或尾注区内,或者位于普通视图的脚注或尾注窗格中,则本参数返回 true。详细内容,请参阅前面的 wdinfootnote 和 wdinendnote 的说明。
537 //wdinheaderfooter 如果指定的所选内容或区域位于页眉或页脚窗格中,或者位于页面视图的页眉或页脚中,则本参数返回 true。
538 //wdinmasterdocument 如果指定的所选内容或区域位于主控文档中,则本参数返回 true。
539 //wdinwordmail 返回一个值,该值表明了所选内容或区域的的位置,如下表所示。值 位置
540 //0 所选内容或区域不在一条电子邮件消息中。
541 //1 所选内容或区域位于正在发送的电子邮件中。
542 //2 所选内容或区域位于正在阅读的电子邮件中。
543 //wdmaximumnumberofcolumns 返回所选内容或区域中任何行的最大表格列数。
544 //wdmaximumnumberofrows 返回指定的所选内容或区域中表格的最大行数。
545 //wdnumberofpagesindocument 返回与所选内容或区域相关联的文档的页数。
546 //wdnumlock 如果 num lock 有效,则本参数返回 true。
547 //wdovertype 如果改写模式有效,则本参数返回 true。可用 overtype 属性改变改写模式的状态。
548 //wdreferenceoftype 返回一个值,该值表明所选内容相对于脚注、尾注或批注引用的位置,如下表所示。 值 描述
549 //— 1 所选内容或区域包含、但不只限定于脚注、尾注或批注引用中。
550 //0 所选内容或区域不在脚注、尾注或批注引用之前。
551 //1 所选内容或区域位于脚注引用之前。
552 //2 所选内容或区域位于尾注引用之前。
553 //3 所选内容或区域位于批注引用之前。
554 //wdrevisionmarking 如果修订功能处于活动状态,则本参数返回 true。
555 //wdselectionmode 返回一个值,该值表明当前的选定模式,如下表所示。 值 选定模式
556 //0 常规选定
557 //1 扩展选定
558 //2 列选定
559 //wdstartofrangecolumnnumber 返回所选内容或区域的起点所在的表格的列号。
560 //wdstartofrangerownumber 返回所选内容或区域的起点所在的表格的行号。
561 //wdverticalpositionrelativetopage 返回所选内容或区域的垂直位置,即所选内容的上边与页面的上边之间的距离,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。
562 //wdverticalpositionrelativetotextboundary 返回所选内容或区域相对于周围最近的正文边界的上边的垂直位置,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。
563 //wdwithintable 如果所选内容位于一个表格中,则本参数返回 true。
564 //wdzoompercentage 返回由 percentage 属性设置的当前的放大百分比。
565
566 #endregion
567
568 光标移动#region 光标移动
569 //移动光标
570 //光标下移3行 上移3行
571 object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
572 object count = 3;
573 WordApp.Selection.MoveEnd( ref unit, ref count );
574 WordApp.Selection.MoveUp( ref unit, ref count, ref oMissing );
575
576 //Microsoft.Office.Interop.Word.WdUnits说明
577 //wdCell A cell.
578 //wdCharacter A character.
579 //wdCharacterFormatting Character formatting.
580 //wdColumn A column.
581 //wdItem The selected item.
582 //wdLine A line. //行
583 //wdParagraph A paragraph.
584 //wdParagraphFormatting Paragraph formatting.
585 //wdRow A row.
586 //wdScreen The screen dimensions.
587 //wdSection A section.
588 //wdSentence A sentence.
589 //wdStory A story.
590 //wdTable A table.
591 //wdWindow A window.
592 //wdWord A word.
593
594 //录制的vb宏
595 // ,移动光标至当前行首
596 // Selection.HomeKey unit:=wdLine
597 // '移动光标至当前行尾
598 // Selection.EndKey unit:=wdLine
599 // '选择从光标至当前行首的内容
600 // Selection.HomeKey unit:=wdLine, Extend:=wdExtend
601 // '选择从光标至当前行尾的内容
602 // Selection.EndKey unit:=wdLine, Extend:=wdExtend
603 // '选择当前行
604 // Selection.HomeKey unit:=wdLine
605 // Selection.EndKey unit:=wdLine, Extend:=wdExtend
606 // '移动光标至文档开始
607 // Selection.HomeKey unit:=wdStory
608 // '移动光标至文档结尾
609 // Selection.EndKey unit:=wdStory
610 // '选择从光标至文档开始的内容
611 // Selection.HomeKey unit:=wdStory, Extend:=wdExtend
612 // '选择从光标至文档结尾的内容
613 // Selection.EndKey unit:=wdStory, Extend:=wdExtend
614 // '选择文档全部内容(从WholeStory可猜出Story应是当前文档的意思)
615 // Selection.WholeStory
616 // '移动光标至当前段落的开始
617 // Selection.MoveUp unit:=wdParagraph
618 // '移动光标至当前段落的结尾
619 // Selection.MoveDown unit:=wdParagraph
620 // '选择从光标至当前段落开始的内容
621 // Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend
622 // '选择从光标至当前段落结尾的内容
623 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
624 // '选择光标所在段落的内容
625 // Selection.MoveUp unit:=wdParagraph
626 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
627 // '显示选择区的开始与结束的位置,注意:文档第1个字符的位置是0
628 // MsgBox ("第" & Selection.Start & "个字符至第" & Selection.End & "个字符")
629 // '删除当前行
630 // Selection.HomeKey unit:=wdLine
631 // Selection.EndKey unit:=wdLine, Extend:=wdExtend
632 // Selection.Delete
633 // '删除当前段落
634 // Selection.MoveUp unit:=wdParagraph
635 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
636 // Selection.Delete
637
638
639 //表格的光标移动
640 //光标到当前光标所在表格的地单元格
641 WordApp.Selection.Tables[1].Cell( 1, 1 ).Select();
642 //unit对象定义
643 object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式
644 object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;/**//**//**////extend对光标移动区域进行扩展选择
645 object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文档行方式,可以看成表格一行.不过和wdRow有区别
646 object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,对于表格可以选择到表格行后的换车符,对于跨行合并的行选择,我能找到的最简单方式
647 //object count = 1;//光标移动量
648
649 #endregion
650 }
651 #endregion
652
653 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。#region 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
654 /**//// <summary>
655 /// 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
656 /// </summary>
657 /// <param name="fileName">word文档</param>
658 /// <param name="rowIndex">行</param>
659 /// <param name="colIndex">列</param>
660 /// <returns>返回数据</returns>
661 public static string ReadWord_tableContentByCell( string fileName, int rowIndex, int colIndex )
662 {
663 ApplicationClass cls = null;
664 Document doc = null;
665 Table table = null;
666 object missing = Missing.Value;
667 object path = fileName;
668 cls = new ApplicationClass();
669 try
670 {
671 doc = cls.Documents.Open
672 ( ref path, ref missing, ref missing, ref missing,
673 ref missing, ref missing, ref missing, ref missing,
674 ref missing, ref missing, ref missing, ref missing,
675 ref missing, ref missing, ref missing, ref missing );
676 table = doc.Tables[1];
677 string text = table.Cell( rowIndex, colIndex ).Range.Text.ToString();
678 text = text.Substring( 0, text.Length - 2 ); //去除尾部的mark
679 return text;
680 }
681 catch( Exception ex )
682 {
683 return ex.Message;
684 }
685 finally
686 {
687 if( doc != null )
688 doc.Close( ref missing, ref missing, ref missing );
689 cls.Quit( ref missing, ref missing, ref missing );
690 }
691 }
692 #endregion
693
694 修改word表格中指定单元格的数据#region 修改word表格中指定单元格的数据
695 /**//// <summary>
696 /// 修改word表格中指定单元格的数据
697 /// </summary>
698 /// <param name="fileName">word文档包括路径</param>
699 /// <param name="rowIndex">行</param>
700 /// <param name="colIndex">列</param>
701 /// <param name="content"></param>
702 /// <returns></returns>
703 public static bool UpdateWordTableByCell( string fileName, int rowIndex, int colIndex, string content )
704 {
705 ApplicationClass cls = null;
706 Document doc = null;
707 Table table = null;
708 object missing = Missing.Value;
709 object path = fileName;
710 cls = new ApplicationClass();
711 try
712 {
713 doc = cls.Documents.Open
714 ( ref path, ref missing, ref missing, ref missing,
715 ref missing, ref missing, ref missing, ref missing,
716 ref missing, ref missing, ref missing, ref missing,
717 ref missing, ref missing, ref missing, ref missing );
718
719 table = doc.Tables[1];
720 //doc.Range( ref 0, ref 0 ).InsertParagraphAfter();//插入回车
721 table.Cell( rowIndex, colIndex ).Range.InsertParagraphAfter();//.Text = content;
722 return true;
723 }
724 catch
725 {
726 return false;
727 }
728 finally
729 {
730 if( doc != null )
731 {
732 doc.Close( ref missing, ref missing, ref missing );
733 cls.Quit( ref missing, ref missing, ref missing );
734 }
735 }
736 }
737 #endregion
738
739 清楚word进程#region 清楚word进程
740 /**//// <summary>
741 /// 清楚word进程
742 /// </summary>
743 public static void KillWordProcess()
744 {
745 System.Diagnostics.Process[] myPs;
746 myPs = System.Diagnostics.Process.GetProcesses();
747 foreach( System.Diagnostics.Process p in myPs )
748 {
749 if( p.Id != 0 )
750 {
751 string myS = "WINWORD.EXE" + p.ProcessName + " ID:" + p.Id.ToString();
752 try
753 {
754 if( p.Modules != null )
755 if( p.Modules.Count > 0 )
756 {
757 System.Diagnostics.ProcessModule pm = p.Modules[0];
758 myS += "\n Modules[0].FileName:" + pm.FileName;
759 myS += "\n Modules[0].ModuleName:" + pm.ModuleName;
760 myS += "\n Modules[0].FileVersionInfo:\n" + pm.FileVersionInfo.ToString();
761 if( pm.ModuleName.ToLower() == "winword.exe" )
762 p.Kill();
763 }
764 }
765 catch
766 { }
767 finally
768 {
769 ;
770 }
771 }
772 }
773 }
774 #endregion
775
776 清楚excel进程#region 清楚excel进程
777 /**//// <summary>
778 /// 清楚excel进程
779 /// </summary>
780 public static void KillExcelProcess()
781 {
782 System.Diagnostics.Process[] myPs;
783 myPs = System.Diagnostics.Process.GetProcesses();
784 foreach( System.Diagnostics.Process p in myPs )
785 {
786 if( p.Id != 0 )
787 {
788 string myS = "excel.EXE" + p.ProcessName + " ID:" + p.Id.ToString();
789 try
790 {
791 if( p.Modules != null )
792 if( p.Modules.Count > 0 )
793 {
794 System.Diagnostics.ProcessModule pm = p.Modules[0];
795 myS += "\n Modules[0].FileName:" + pm.FileName;
796 myS += "\n Modules[0].ModuleName:" + pm.ModuleName;
797 myS += "\n Modules[0].FileVersionInfo:\n" + pm.FileVersionInfo.ToString();
798 if( pm.ModuleName.ToLower() == "excel.exe" )
799 p.Kill();
800 }
801 }
802 catch
803 { }
804 finally
805 {
806 ;
807 }
808 }
809 }
810 }
811 #endregion
812
813 网页内容或导入word或excel#region 网页内容或导入word或excel
814 /**//// <summary>
815 /// 网页内容保存或导出为word或excel
816 /// </summary>
817 /// <param name="url">网页地址</param>
818 /// <param name="num">0为导出word,1为导出excel</param>
819 public static void SaveOrOutData( string url, int num )//导出数据的函数0为word,1为Excel
820 {
821 WebRequest req = WebRequest.Create( url );
822 WebResponse resp = req.GetResponse();
823 StreamReader sr = new StreamReader( resp.GetResponseStream(), System.Text.Encoding.UTF8 );
824 string x = sr.ReadToEnd();
825
826 System.Web.HttpContext.Current.Response.Clear();
827 System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( "gb2312" );
828 string fName = DateTime.Now.ToString( "yyyy-MM-dd-ss" );
829 if( num == 0 )
830 {
831 fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".doc";
832 System.Web.HttpContext.Current.Response.ContentType = "application/ms-word";
833 }
834 else
835 {
836 fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".xls";
837 System.Web.HttpContext.Current.Response.ContentType = "application nd.xls";
838 }
839 System.Web.HttpContext.Current.Response.AddHeader( "content-disposition", "attachment;filename=" + fName );
840 System.Web.HttpContext.Current.Response.Write( getBodyContent( x ) );//获取table标签
841 System.Web.HttpContext.Current.Response.Flush();
842 System.Web.HttpContext.Current.Response.End();
843 }
844
845 /**//// <summary>
846 /// 获取网页table标签的内容
847 /// </summary>
848 /// <param name="input">html代码</param>
849 /// <returns></returns>
850 private static string getBodyContent( string input )
851 {
852 string pattern = @"<table.*?</table>";
853 Regex reg = new Regex( pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase );
854 Match mc = reg.Match( input );
855 string bodyContent = "";
856 if( mc.Success )
857 {
858 bodyContent = mc.Value;
859 }
860 return bodyContent;
861 }
862 #endregion
863
864 判断系统是否装excel#region 判断系统是否装excel
865 /**//// <summary>
866 /// 判断系统是否装excel
867 /// </summary>
868 /// <returns></returns>
869 public static bool IsInstallExcel()
870 {
871 RegistryKey machineKey = Registry.LocalMachine;
872 if( IsInstallExcelByVersion( "12.0", machineKey ) )
873 {
874 return true;
875 }
876 if( IsInstallExcelByVersion( "11.0", machineKey ) )
877 {
878 return true;
879 }
880 return false;
881 }
882
883 /**//// <summary>
884 /// 判断系统是否装某版本的excel
885 /// </summary>
886 /// <param name="strVersion">版本号</param>
887 /// <param name="machineKey"></param>
888 /// <returns></returns>
889 private static bool IsInstallExcelByVersion( string strVersion, RegistryKey machineKey )
890 {
891 try
892 {
893 RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Excel" ).OpenSubKey( "InstallRoot" );
894 if( installKey == null )
895 {
896 return false;
897 }
898 return true;
899 }
900 catch
901 {
902 return false;
903 }
904 }
905 #endregion
906
907 判断系统是否装word#region 判断系统是否装word
908 /**//// <summary>
909 /// 判断系统是否装word
910 /// </summary>
911 /// <returns></returns>
912 public static bool IsInstallWord()
913 {
914 RegistryKey machineKey = Registry.LocalMachine;
915 if( IsInstallExcelByVersion( "12.0", machineKey ) )
916 {
917 return true;
918 }
919 if( IsInstallExcelByVersion( "11.0", machineKey ) )
920 {
921 return true;
922 }
923 return false;
924 }
925
926 /**//// <summary>
927 /// 判断系统是否装某版本的word
928 /// </summary>
929 /// <param name="strVersion">版本号</param>
930 /// <param name="machineKey"></param>
931 /// <returns></returns>
932 private static bool IsInstallWordByVersion( string strVersion, RegistryKey machineKey )
933 {
934 try
935 {
936 RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Word" ).OpenSubKey( "InstallRoot" );
937 if( installKey == null )
938 {
939 return false;
940 }
941 return true;
942 }
943 catch
944 {
945 return false;
946 }
947 }
948 #endregion
949 }
950}
951
1using System;
2using System.Collections.Generic;
3using System.Text;
4using Microsoft.Office.Interop.Word;
5using System.IO;
6using System.Web;
7using System.Data;
8using System.Reflection;
9using Microsoft.Win32;
10using System.Text.RegularExpressions;
11using System.Net;
12
13namespace OfficeOperate
14{
15 public class WordOperate
16 {
17 动态生成Word文档并填充数据#region 动态生成Word文档并填充数据
18 /**//// <summary>
19 /// 动态生成Word文档并填充数据
20 /// </summary>
21 /// <returns>返回自定义信息</returns>
22 public static string CreateWordFile()
23 {
24 string message = "";
25 try
26 {
27 Object oMissing = System.Reflection.Missing.Value;
28 string dir = System.Web.HttpContext.Current.Server.MapPath( "" );//首先在类库添加using System.web的引用
29 if( !Directory.Exists( dir + "\\file" ) )
30 {
31 Directory.CreateDirectory( dir + "\\file" ); //创建文件所在目录
32 }
33 string name = DateTime.Now.ToLongDateString() + ".doc";
34 object filename = dir + "\\file\\" + name; //文件保存路径
35 //创建Word文档
36 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
37 Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
38
39 /**/////添加页眉方法一:
40 //WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
41 //WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
42 //WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "无锡全真通科技有限公司" );//页眉内容
43
44 //添加页眉方法二:
45 if( WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView )
46 {
47 WordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
48 }
49 WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
50 string sHeader = "页眉内容";
51 WordApp.Selection.HeaderFooter.LinkToPrevious = false;
52 WordApp.Selection.HeaderFooter.Range.Text = sHeader;
53 WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
54
55
56 //WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
57 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;//设置左对齐
58 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置
59
60 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
61
62 //移动焦点并换行
63 object count = 14;
64 object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
65 WordApp.Selection.MoveDown( ref WdLine, ref count, ref oMissing );//移动焦点
66 WordApp.Selection.TypeParagraph();//插入段落
67
68 //文档中创建表格
69 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add( WordApp.Selection.Range, 12, 3, ref oMissing, ref oMissing );
70 //设置表格样式
71 newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
72 newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
73 newTable.Columns[1].Width = 100f;
74 newTable.Columns[2].Width = 220f;
75 newTable.Columns[3].Width = 105f;
76
77 //填充表格内容
78 newTable.Cell( 1, 1 ).Range.Text = "产品详细信息表";
79 newTable.Cell( 1, 1 ).Range.Bold = 2;//设置单元格中字体为粗体
80 //合并单元格
81 newTable.Cell( 1, 1 ).Merge( newTable.Cell( 1, 3 ) );
82 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
83 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
84
85 //填充表格内容
86 newTable.Cell( 2, 1 ).Range.Text = "产品基本信息";
87 newTable.Cell( 2, 1 ).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
88 //合并单元格
89 newTable.Cell( 2, 1 ).Merge( newTable.Cell( 2, 3 ) );
90 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
91
92 //填充表格内容
93 newTable.Cell( 3, 1 ).Range.Text = "品牌名称:";
94 newTable.Cell( 3, 2 ).Range.Text = "BrandName";
95 //纵向合并单元格
96 newTable.Cell( 3, 3 ).Select();//选中一行
97 object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
98 object moveCount = 5;
99 object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
100 WordApp.Selection.MoveDown( ref moveUnit, ref moveCount, ref moveExtend );
101 WordApp.Selection.Cells.Merge();
102
103 //插入图片
104 if( File.Exists( System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" ) ) )
105 {
106 string FileName = System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" );//图片所在路径
107 object LinkToFile = false;
108 object SaveWithDocument = true;
109 object Anchor = WordDoc.Application.Selection.Range;
110 WordDoc.Application.ActiveDocument.InlineShapes.AddPicture( FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor );
111 WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
112 WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
113 }
114 //将图片设置为四周环绕型
115 Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
116 s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
117
118 newTable.Cell( 12, 1 ).Range.Text = "产品特殊属性";
119 newTable.Cell( 12, 1 ).Merge( newTable.Cell( 12, 3 ) );
120 //在表格中增加行
121 WordDoc.Content.Tables[1].Rows.Add( ref oMissing );
122
123 WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
124 WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
125
126 //文件保存
127 WordDoc.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 );
128 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
129 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
130 message = name + "文档生成成功";
131 }
132 catch
133 {
134 message = "文件导出异常!";
135 }
136 return message;
137 }
138 #endregion
139
140 创建并打开一个空的word文档进行编辑#region 创建并打开一个空的word文档进行编辑
141 /**//// <summary>
142 /// 创建并打开一个空的word文档进行编辑
143 /// </summary>
144 public static void OpenNewWordFileToEdit()
145 {
146 object oMissing = System.Reflection.Missing.Value;
147 Microsoft.Office.Interop.Word.Application WordApp;
148 Microsoft.Office.Interop.Word.Document WordDoc;
149 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
150 WordApp.Visible = true;
151 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
152 }
153 #endregion
154
155 创建word文档#region 创建word文档
156 /**//// <summary>
157 /// 创建word文档
158 /// </summary>
159 /// <returns></returns>
160 public static string createWord()
161 {
162 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
163 Document WordDoc;
164 string strContent = "";
165
166 object strFileName = System.Web.HttpContext.Current.Server.MapPath( "test.doc " );
167 if( System.IO.File.Exists( (string)strFileName ) )
168 System.IO.File.Delete( (string)strFileName );
169 Object oMissing = System.Reflection.Missing.Value;
170 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
171
172 将数据库中读取得数据写入到word文件中#region 将数据库中读取得数据写入到word文件中
173 strContent = "你好\n\n\r ";
174 WordDoc.Paragraphs.Last.Range.Text = strContent;
175 strContent = "这是测试程序 ";
176 WordDoc.Paragraphs.Last.Range.Text = strContent;
177 #endregion
178
179 //将WordDoc文档对象的内容保存为DOC文档
180 WordDoc.SaveAs( ref strFileName, 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 );
181 //关闭WordDoc文档对象
182 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
183 //关闭WordApp组件对象
184 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
185
186 string message = strFileName + "\r\n " + "创建成功 ";
187 return message;
188 }
189 #endregion
190
191 把Word文档装化为Html文件#region 把Word文档装化为Html文件
192 /**//// <summary>
193 /// 把Word文档装化为Html文件
194 /// </summary>
195 /// <param name="strFileName">要转换的Word文档</param>
196 public static void WordToHtml( string strFileName )
197 {
198 string saveFileName = strFileName + DateTime.Now.ToString( "yyyy-MM-dd-HH-mm-ss" ) + ".html";
199 WordToHtml( strFileName, saveFileName );
200 }
201 /**//// <summary>
202 /// 把Word文档装化为Html文件
203 /// </summary>
204 /// <param name="strFileName">要转换的Word文档</param>
205 /// <param name="strSaveFileName">要生成的具体的Html页面</param>
206 public static void WordToHtml( string strFileName, string strSaveFileName )
207 {
208 Microsoft.Office.Interop.Word.ApplicationClass WordApp;
209 Microsoft.Office.Interop.Word.Document WordDoc;
210 Object oMissing = System.Reflection.Missing.Value;
211 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
212 object fileName = strFileName;
213
214 WordDoc = WordApp.Documents.Open( ref fileName,
215 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
216 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
217 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing );
218
219 Type wordType = WordApp.GetType();
220 // 打开文件
221 Type docsType = WordApp.Documents.GetType();
222 // 转换格式,另存为
223 Type docType = WordDoc.GetType();
224 object saveFileName = strSaveFileName;
225 docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML } );
226
227 其它格式:#region 其它格式:
228 /**//**/
229 /**////wdFormatHTML
230 ///wdFormatDocument
231 ///wdFormatDOSText
232 ///wdFormatDOSTextLineBreaks
233 ///wdFormatEncodedText
234 ///wdFormatRTF
235 ///wdFormatTemplate
236 ///wdFormatText
237 ///wdFormatTextLineBreaks
238 ///wdFormatUnicodeText
239 //-----------------------------------------------------------------------------------
240 // docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
241 // null, WordDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
242 // 退出 Word
243 //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
244 // null, WordApp, null );
245 #endregion
246 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
247 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
248 }
249 #endregion
250
251 导入模板#region 导入模板
252 /**//// <summary>
253 /// 导入模板
254 /// </summary>
255 /// <param name="filePath">模板文档路径</param>
256 public static void ImportTemplate( string filePath )
257 {
258 object oMissing = System.Reflection.Missing.Value;
259 Microsoft.Office.Interop.Word.Application WordApp;
260 Microsoft.Office.Interop.Word.Document WordDoc;
261 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
262 WordApp.Visible = true;
263 object fileName = filePath;
264 WordDoc = WordApp.Documents.Add( ref fileName, ref oMissing, ref oMissing, ref oMissing );
265 }
266 #endregion
267
268 word中添加新表#region word中添加新表
269 /**//// <summary>
270 /// word中添加新表
271 /// </summary>
272 public static void AddTable()
273 {
274 object oMissing = System.Reflection.Missing.Value;
275 Microsoft.Office.Interop.Word.Application WordApp;
276 Microsoft.Office.Interop.Word.Document WordDoc;
277 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
278 WordApp.Visible = true;
279 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
280
281 object start = 0;
282 object end = 0;
283 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
284 WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );//3行4列的表
285 }
286 #endregion
287
288 在表中插入新行#region 在表中插入新行
289 /**//// <summary>
290 /// 在表中插入新的1行
291 /// </summary>
292 public static void AddRow()
293 {
294 object oMissing = System.Reflection.Missing.Value;
295 Microsoft.Office.Interop.Word.Application WordApp;
296 Microsoft.Office.Interop.Word.Document WordDoc;
297 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
298 WordApp.Visible = true;
299 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
300
301 object start = 0;
302 object end = 0;
303 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
304 WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
305
306 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
307 object beforeRow = newTable.Rows[1];
308 newTable.Rows.Add( ref beforeRow );
309 }
310 #endregion
311
312 分离单元格#region 分离单元格
313 /**//// <summary>
314 /// 合并单元格
315 /// </summary>
316 public static void CombinationCell()
317 {
318 object oMissing = System.Reflection.Missing.Value;
319 Microsoft.Office.Interop.Word.Application WordApp;
320 Microsoft.Office.Interop.Word.Document WordDoc;
321 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
322 WordApp.Visible = true;
323 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
324
325 object start = 0;
326 object end = 0;
327 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
328 WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
329
330 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
331 object beforeRow = newTable.Rows[1];
332 newTable.Rows.Add( ref beforeRow );
333
334 Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 2, 1 );//2行1列合并2行2列为一起
335 cell.Merge( newTable.Cell( 2, 2 ) );
336 //cell.Merge( newTable.Cell( 1, 3 ) );
337 }
338 #endregion
339
340 分离单元格#region 分离单元格
341 /**//// <summary>
342 /// 分离单元格
343 /// </summary>
344 public static void SeparateCell()
345 {
346 object oMissing = System.Reflection.Missing.Value;
347 Microsoft.Office.Interop.Word.Application WordApp;
348 Microsoft.Office.Interop.Word.Document WordDoc;
349 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
350 WordApp.Visible = true;
351 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
352
353 object start = 0;
354 object end = 0;
355 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
356 WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
357
358 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
359 object beforeRow = newTable.Rows[1];
360 newTable.Rows.Add( ref beforeRow );
361
362 Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 1, 1 );
363 cell.Merge( newTable.Cell( 1, 2 ) );
364
365 object Rownum = 2;
366 object Columnnum = 2;
367 cell.Split( ref Rownum, ref Columnnum );
368 }
369 #endregion
370
371 通过段落控制插入Insert a paragraph at the beginning of the document.#region 通过段落控制插入Insert a paragraph at the beginning of the document.
372 /**//// <summary>
373 /// 通过段落控制插入Insert a paragraph at the beginning of the document.
374 /// </summary>
375 public static void Insert()
376 {
377 object oMissing = System.Reflection.Missing.Value;
378 //object oEndOfDoc = "\\endofdoc"; /**//* \endofdoc is a predefined bookmark */
379
380 //Start Word and create a new document.
381 Microsoft.Office.Interop.Word.Application WordApp;
382 Microsoft.Office.Interop.Word.Document WordDoc;
383 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
384 WordApp.Visible = true;
385
386 WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
387
388 //Insert a paragraph at the beginning of the document.
389 Microsoft.Office.Interop.Word.Paragraph oPara1;
390 oPara1 = WordDoc.Content.Paragraphs.Add( ref oMissing );
391 oPara1.Range.Text = "Heading 1";
392 oPara1.Range.Font.Bold = 1;
393 oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
394 oPara1.Range.InsertParagraphAfter();
395 }
396 #endregion
397
398 word文档设置及获取光标位置#region word文档设置及获取光标位置
399 /**//// <summary>
400 /// word文档设置及获取光标位置
401 /// </summary>
402 public static void WordSet()
403 {
404 object oMissing = System.Reflection.Missing.Value;
405 Microsoft.Office.Interop.Word.Application WordApp;
406 Microsoft.Office.Interop.Word.Document WordDoc;
407 WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
408
409 文档格式设置#region 文档格式设置
410 WordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0;//行编号
411 WordApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//页面方向
412 WordApp.ActiveDocument.PageSetup.TopMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//上页边距
413 WordApp.ActiveDocument.PageSetup.BottomMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//下页边距
414 WordApp.ActiveDocument.PageSetup.LeftMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//左页边距
415 WordApp.ActiveDocument.PageSetup.RightMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//右页边距
416 WordApp.ActiveDocument.PageSetup.Gutter = WordApp.CentimetersToPoints( float.Parse( "0" ) );//装订线位置
417 WordApp.ActiveDocument.PageSetup.HeaderDistance = WordApp.CentimetersToPoints( float.Parse( "1.5" ) );//页眉
418 WordApp.ActiveDocument.PageSetup.FooterDistance = WordApp.CentimetersToPoints( float.Parse( "1.75" ) );//页脚
419 WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints( float.Parse( "21" ) );//纸张宽度
420 WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints( float.Parse( "29.7" ) );//纸张高度
421 WordApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
422 WordApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
423 WordApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//节的起始位置:新建页
424 WordApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//页眉页脚-奇偶页不同
425 WordApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//页眉页脚-首页不同
426 WordApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//页面垂直对齐方式
427 WordApp.ActiveDocument.PageSetup.SuppressEndnotes = 0;//不隐藏尾注
428 WordApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不设置首页的内外边距
429 WordApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不双面打印
430 WordApp.ActiveDocument.PageSetup.BookFoldPrinting = false;//不设置手动双面正面打印
431 WordApp.ActiveDocument.PageSetup.BookFoldRevPrinting = false;//不设置手动双面背面打印
432 WordApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默认份数
433 WordApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//装订线位于左侧
434 WordApp.ActiveDocument.PageSetup.LinesPage = 40;//默认页行数量
435 WordApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式为“只指定行网格”
436 #endregion
437
438 段落格式设定#region 段落格式设定
439 WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//左缩进
440 WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//右缩进
441 WordApp.Selection.ParagraphFormat.SpaceBefore = float.Parse( "0" );//段前间距
442 WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;//
443 WordApp.Selection.ParagraphFormat.SpaceAfter = float.Parse( "0" );//段后间距
444 WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;//
445 WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//单倍行距
446 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端对齐
447 WordApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制
448 WordApp.Selection.ParagraphFormat.KeepWithNext = 0;//与下段同页
449 WordApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分页
450 WordApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分页
451 WordApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行号
452 WordApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字
453 WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//首行缩进
454 WordApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText;
455 WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse( "0" );
456 WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse( "0" );
457 WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse( "0" );
458 WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse( "0" );
459 WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse( "0" );
460 WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1;
461 WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = 0;
462 WordApp.Selection.ParagraphFormat.FarEastLineBreakControl = 1;
463 WordApp.Selection.ParagraphFormat.WordWrap = 1;
464 WordApp.Selection.ParagraphFormat.HangingPunctuation = 1;
465 WordApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0;
466 WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1;
467 WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1;
468 WordApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto;
469 #endregion
470
471 字体格式设定#region 字体格式设定
472 WordApp.Selection.Font.NameFarEast = "华文中宋";
473 WordApp.Selection.Font.NameAscii = "Times New Roman";
474 WordApp.Selection.Font.NameOther = "Times New Roman";
475 WordApp.Selection.Font.Name = "宋体";
476 WordApp.Selection.Font.Size = float.Parse( "14" );
477 WordApp.Selection.Font.Bold = 0;
478 WordApp.Selection.Font.Italic = 0;
479 WordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
480 WordApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
481 WordApp.Selection.Font.StrikeThrough = 0;//删除线
482 WordApp.Selection.Font.DoubleStrikeThrough = 0;//双删除线
483 WordApp.Selection.Font.Outline = 0;//空心
484 WordApp.Selection.Font.Emboss = 0;//阳文
485 WordApp.Selection.Font.Shadow = 0;//阴影
486 WordApp.Selection.Font.Hidden = 0;//隐藏文字
487 WordApp.Selection.Font.SmallCaps = 0;//小型大写字母
488 WordApp.Selection.Font.AllCaps = 0;//全部大写字母
489 WordApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
490 WordApp.Selection.Font.Engrave = 0;//阴文
491 WordApp.Selection.Font.Superscript = 0;//上标
492 WordApp.Selection.Font.Subscript = 0;//下标
493 WordApp.Selection.Font.Spacing = float.Parse( "0" );//字符间距
494 WordApp.Selection.Font.Scaling = 100;//字符缩放
495 WordApp.Selection.Font.Position = 0;//位置
496 WordApp.Selection.Font.Kerning = float.Parse( "1" );//字体间距调整
497 WordApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果
498 WordApp.Selection.Font.DisableCharacterSpaceGrid = false;
499 WordApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone;
500
501 #endregion
502
503 获取光标位置#region 获取光标位置
504 /**/////get_Information
505 WordApp.Selection.get_Information( WdInformation.wdActiveEndPageNumber );
506 //关于行号-页号-列号-位置
507 //information 属性
508 //返回有关指定的所选内容或区域的信息。variant 类型,只读。
509 //expression.information(type)
510 //expression 必需。该表达式返回一个 range 或 selection 对象。
511 //type long 类型,必需。需要返回的信息。可取下列 wdinformation 常量之一:
512 //wdactiveendadjustedpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾。如果设置了一个起始页码,并对页码进行了手工调整,则返回调整过的页码。
513 //wdactiveendpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾,页码从文档的开头开始计算而不考虑对页码的任何手工调整。
514 //wdactiveendsectionnumber 返回节号,在该节中包含了指定的所选内容或区域的活动结尾。
515 //wdatendofrowmarker 如果指定的所选内容或区域位于表格的行结尾标记处,则本参数返回 true。
516 //wdcapslock 如果大写字母锁定模式有效,则本参数返回 true。
517 //wdendofrangecolumnnumber 返回表格列号,在该表格列中包含了指定的所选内容或区域的活动结尾。
518 //wdendofrangerownumber 返回表格行号,在该表格行包含了指定的所选内容或区域的活动结尾。
519 //wdfirstcharactercolumnnumber 返回指定的所选内容或区域中第一个字符的位置。如果所选内容或区域是折叠的,则返回所选内容或区域右侧紧接着的字符编号。
520 //wdfirstcharacterlinenumber 返回所选内容中第一个字符的行号。如果 pagination 属性为 false,或 draft 属性为 true,则返回 - 1。
521 //wdframeisselected 如果所选内容或区域是一个完整的图文框文本框,则本参数返回 true。
522 //wdheaderfootertype 返回一个值,该值表明包含了指定的所选内容或区域的页眉或页脚的类型,如下表所示。 值 页眉或页脚的类型
523 //- 1 无
524 //0 偶数页页眉
525 //1 奇数页页眉
526 //2 偶数页页脚
527 //3 奇数页页脚
528 //4 第一个页眉
529 //5 第一个页脚
530 //wdhorizontalpositionrelativetopage 返回指定的所选内容或区域的水平位置。该位置是所选内容或区域的左边与页面的左边之间的距离,以磅为单位。如果所选内容或区域不可见,则返回 - 1。
531 //wdhorizontalpositionrelativetotextboundary 返回指定的所选内容或区域相对于周围最近的正文边界的左边的水平位置,以磅为单位。如果所选内容或区域没有显示在当前屏幕,则本参数返回 - 1。
532 //wdinclipboard 有关此常量的详细内容,请参阅 microsoft office 98 macintosh 版的语言参考帮助。
533 //wdincommentpane 如果指定的所选内容或区域位于批注窗格,则返回 true。
534 //wdinendnote 如果指定的所选内容或区域位于页面视图的尾注区内,或者位于普通视图的尾注窗格中,则本参数返回 true。
535 //wdinfootnote 如果指定的所选内容或区域位于页面视图的脚注区内,或者位于普通视图的脚注窗格中,则本参数返回 true。
536 //wdinfootnoteendnotepane 如果指定的所选内容或区域位于页面视图的脚注或尾注区内,或者位于普通视图的脚注或尾注窗格中,则本参数返回 true。详细内容,请参阅前面的 wdinfootnote 和 wdinendnote 的说明。
537 //wdinheaderfooter 如果指定的所选内容或区域位于页眉或页脚窗格中,或者位于页面视图的页眉或页脚中,则本参数返回 true。
538 //wdinmasterdocument 如果指定的所选内容或区域位于主控文档中,则本参数返回 true。
539 //wdinwordmail 返回一个值,该值表明了所选内容或区域的的位置,如下表所示。值 位置
540 //0 所选内容或区域不在一条电子邮件消息中。
541 //1 所选内容或区域位于正在发送的电子邮件中。
542 //2 所选内容或区域位于正在阅读的电子邮件中。
543 //wdmaximumnumberofcolumns 返回所选内容或区域中任何行的最大表格列数。
544 //wdmaximumnumberofrows 返回指定的所选内容或区域中表格的最大行数。
545 //wdnumberofpagesindocument 返回与所选内容或区域相关联的文档的页数。
546 //wdnumlock 如果 num lock 有效,则本参数返回 true。
547 //wdovertype 如果改写模式有效,则本参数返回 true。可用 overtype 属性改变改写模式的状态。
548 //wdreferenceoftype 返回一个值,该值表明所选内容相对于脚注、尾注或批注引用的位置,如下表所示。 值 描述
549 //— 1 所选内容或区域包含、但不只限定于脚注、尾注或批注引用中。
550 //0 所选内容或区域不在脚注、尾注或批注引用之前。
551 //1 所选内容或区域位于脚注引用之前。
552 //2 所选内容或区域位于尾注引用之前。
553 //3 所选内容或区域位于批注引用之前。
554 //wdrevisionmarking 如果修订功能处于活动状态,则本参数返回 true。
555 //wdselectionmode 返回一个值,该值表明当前的选定模式,如下表所示。 值 选定模式
556 //0 常规选定
557 //1 扩展选定
558 //2 列选定
559 //wdstartofrangecolumnnumber 返回所选内容或区域的起点所在的表格的列号。
560 //wdstartofrangerownumber 返回所选内容或区域的起点所在的表格的行号。
561 //wdverticalpositionrelativetopage 返回所选内容或区域的垂直位置,即所选内容的上边与页面的上边之间的距离,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。
562 //wdverticalpositionrelativetotextboundary 返回所选内容或区域相对于周围最近的正文边界的上边的垂直位置,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。
563 //wdwithintable 如果所选内容位于一个表格中,则本参数返回 true。
564 //wdzoompercentage 返回由 percentage 属性设置的当前的放大百分比。
565
566 #endregion
567
568 光标移动#region 光标移动
569 //移动光标
570 //光标下移3行 上移3行
571 object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
572 object count = 3;
573 WordApp.Selection.MoveEnd( ref unit, ref count );
574 WordApp.Selection.MoveUp( ref unit, ref count, ref oMissing );
575
576 //Microsoft.Office.Interop.Word.WdUnits说明
577 //wdCell A cell.
578 //wdCharacter A character.
579 //wdCharacterFormatting Character formatting.
580 //wdColumn A column.
581 //wdItem The selected item.
582 //wdLine A line. //行
583 //wdParagraph A paragraph.
584 //wdParagraphFormatting Paragraph formatting.
585 //wdRow A row.
586 //wdScreen The screen dimensions.
587 //wdSection A section.
588 //wdSentence A sentence.
589 //wdStory A story.
590 //wdTable A table.
591 //wdWindow A window.
592 //wdWord A word.
593
594 //录制的vb宏
595 // ,移动光标至当前行首
596 // Selection.HomeKey unit:=wdLine
597 // '移动光标至当前行尾
598 // Selection.EndKey unit:=wdLine
599 // '选择从光标至当前行首的内容
600 // Selection.HomeKey unit:=wdLine, Extend:=wdExtend
601 // '选择从光标至当前行尾的内容
602 // Selection.EndKey unit:=wdLine, Extend:=wdExtend
603 // '选择当前行
604 // Selection.HomeKey unit:=wdLine
605 // Selection.EndKey unit:=wdLine, Extend:=wdExtend
606 // '移动光标至文档开始
607 // Selection.HomeKey unit:=wdStory
608 // '移动光标至文档结尾
609 // Selection.EndKey unit:=wdStory
610 // '选择从光标至文档开始的内容
611 // Selection.HomeKey unit:=wdStory, Extend:=wdExtend
612 // '选择从光标至文档结尾的内容
613 // Selection.EndKey unit:=wdStory, Extend:=wdExtend
614 // '选择文档全部内容(从WholeStory可猜出Story应是当前文档的意思)
615 // Selection.WholeStory
616 // '移动光标至当前段落的开始
617 // Selection.MoveUp unit:=wdParagraph
618 // '移动光标至当前段落的结尾
619 // Selection.MoveDown unit:=wdParagraph
620 // '选择从光标至当前段落开始的内容
621 // Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend
622 // '选择从光标至当前段落结尾的内容
623 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
624 // '选择光标所在段落的内容
625 // Selection.MoveUp unit:=wdParagraph
626 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
627 // '显示选择区的开始与结束的位置,注意:文档第1个字符的位置是0
628 // MsgBox ("第" & Selection.Start & "个字符至第" & Selection.End & "个字符")
629 // '删除当前行
630 // Selection.HomeKey unit:=wdLine
631 // Selection.EndKey unit:=wdLine, Extend:=wdExtend
632 // Selection.Delete
633 // '删除当前段落
634 // Selection.MoveUp unit:=wdParagraph
635 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
636 // Selection.Delete
637
638
639 //表格的光标移动
640 //光标到当前光标所在表格的地单元格
641 WordApp.Selection.Tables[1].Cell( 1, 1 ).Select();
642 //unit对象定义
643 object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式
644 object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;/**//**//**////extend对光标移动区域进行扩展选择
645 object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文档行方式,可以看成表格一行.不过和wdRow有区别
646 object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,对于表格可以选择到表格行后的换车符,对于跨行合并的行选择,我能找到的最简单方式
647 //object count = 1;//光标移动量
648
649 #endregion
650 }
651 #endregion
652
653 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。#region 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
654 /**//// <summary>
655 /// 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
656 /// </summary>
657 /// <param name="fileName">word文档</param>
658 /// <param name="rowIndex">行</param>
659 /// <param name="colIndex">列</param>
660 /// <returns>返回数据</returns>
661 public static string ReadWord_tableContentByCell( string fileName, int rowIndex, int colIndex )
662 {
663 ApplicationClass cls = null;
664 Document doc = null;
665 Table table = null;
666 object missing = Missing.Value;
667 object path = fileName;
668 cls = new ApplicationClass();
669 try
670 {
671 doc = cls.Documents.Open
672 ( ref path, ref missing, ref missing, ref missing,
673 ref missing, ref missing, ref missing, ref missing,
674 ref missing, ref missing, ref missing, ref missing,
675 ref missing, ref missing, ref missing, ref missing );
676 table = doc.Tables[1];
677 string text = table.Cell( rowIndex, colIndex ).Range.Text.ToString();
678 text = text.Substring( 0, text.Length - 2 ); //去除尾部的mark
679 return text;
680 }
681 catch( Exception ex )
682 {
683 return ex.Message;
684 }
685 finally
686 {
687 if( doc != null )
688 doc.Close( ref missing, ref missing, ref missing );
689 cls.Quit( ref missing, ref missing, ref missing );
690 }
691 }
692 #endregion
693
694 修改word表格中指定单元格的数据#region 修改word表格中指定单元格的数据
695 /**//// <summary>
696 /// 修改word表格中指定单元格的数据
697 /// </summary>
698 /// <param name="fileName">word文档包括路径</param>
699 /// <param name="rowIndex">行</param>
700 /// <param name="colIndex">列</param>
701 /// <param name="content"></param>
702 /// <returns></returns>
703 public static bool UpdateWordTableByCell( string fileName, int rowIndex, int colIndex, string content )
704 {
705 ApplicationClass cls = null;
706 Document doc = null;
707 Table table = null;
708 object missing = Missing.Value;
709 object path = fileName;
710 cls = new ApplicationClass();
711 try
712 {
713 doc = cls.Documents.Open
714 ( ref path, ref missing, ref missing, ref missing,
715 ref missing, ref missing, ref missing, ref missing,
716 ref missing, ref missing, ref missing, ref missing,
717 ref missing, ref missing, ref missing, ref missing );
718
719 table = doc.Tables[1];
720 //doc.Range( ref 0, ref 0 ).InsertParagraphAfter();//插入回车
721 table.Cell( rowIndex, colIndex ).Range.InsertParagraphAfter();//.Text = content;
722 return true;
723 }
724 catch
725 {
726 return false;
727 }
728 finally
729 {
730 if( doc != null )
731 {
732 doc.Close( ref missing, ref missing, ref missing );
733 cls.Quit( ref missing, ref missing, ref missing );
734 }
735 }
736 }
737 #endregion
738
739 清楚word进程#region 清楚word进程
740 /**//// <summary>
741 /// 清楚word进程
742 /// </summary>
743 public static void KillWordProcess()
744 {
745 System.Diagnostics.Process[] myPs;
746 myPs = System.Diagnostics.Process.GetProcesses();
747 foreach( System.Diagnostics.Process p in myPs )
748 {
749 if( p.Id != 0 )
750 {
751 string myS = "WINWORD.EXE" + p.ProcessName + " ID:" + p.Id.ToString();
752 try
753 {
754 if( p.Modules != null )
755 if( p.Modules.Count > 0 )
756 {
757 System.Diagnostics.ProcessModule pm = p.Modules[0];
758 myS += "\n Modules[0].FileName:" + pm.FileName;
759 myS += "\n Modules[0].ModuleName:" + pm.ModuleName;
760 myS += "\n Modules[0].FileVersionInfo:\n" + pm.FileVersionInfo.ToString();
761 if( pm.ModuleName.ToLower() == "winword.exe" )
762 p.Kill();
763 }
764 }
765 catch
766 { }
767 finally
768 {
769 ;
770 }
771 }
772 }
773 }
774 #endregion
775
776 清楚excel进程#region 清楚excel进程
777 /**//// <summary>
778 /// 清楚excel进程
779 /// </summary>
780 public static void KillExcelProcess()
781 {
782 System.Diagnostics.Process[] myPs;
783 myPs = System.Diagnostics.Process.GetProcesses();
784 foreach( System.Diagnostics.Process p in myPs )
785 {
786 if( p.Id != 0 )
787 {
788 string myS = "excel.EXE" + p.ProcessName + " ID:" + p.Id.ToString();
789 try
790 {
791 if( p.Modules != null )
792 if( p.Modules.Count > 0 )
793 {
794 System.Diagnostics.ProcessModule pm = p.Modules[0];
795 myS += "\n Modules[0].FileName:" + pm.FileName;
796 myS += "\n Modules[0].ModuleName:" + pm.ModuleName;
797 myS += "\n Modules[0].FileVersionInfo:\n" + pm.FileVersionInfo.ToString();
798 if( pm.ModuleName.ToLower() == "excel.exe" )
799 p.Kill();
800 }
801 }
802 catch
803 { }
804 finally
805 {
806 ;
807 }
808 }
809 }
810 }
811 #endregion
812
813 网页内容或导入word或excel#region 网页内容或导入word或excel
814 /**//// <summary>
815 /// 网页内容保存或导出为word或excel
816 /// </summary>
817 /// <param name="url">网页地址</param>
818 /// <param name="num">0为导出word,1为导出excel</param>
819 public static void SaveOrOutData( string url, int num )//导出数据的函数0为word,1为Excel
820 {
821 WebRequest req = WebRequest.Create( url );
822 WebResponse resp = req.GetResponse();
823 StreamReader sr = new StreamReader( resp.GetResponseStream(), System.Text.Encoding.UTF8 );
824 string x = sr.ReadToEnd();
825
826 System.Web.HttpContext.Current.Response.Clear();
827 System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( "gb2312" );
828 string fName = DateTime.Now.ToString( "yyyy-MM-dd-ss" );
829 if( num == 0 )
830 {
831 fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".doc";
832 System.Web.HttpContext.Current.Response.ContentType = "application/ms-word";
833 }
834 else
835 {
836 fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".xls";
837 System.Web.HttpContext.Current.Response.ContentType = "application nd.xls";
838 }
839 System.Web.HttpContext.Current.Response.AddHeader( "content-disposition", "attachment;filename=" + fName );
840 System.Web.HttpContext.Current.Response.Write( getBodyContent( x ) );//获取table标签
841 System.Web.HttpContext.Current.Response.Flush();
842 System.Web.HttpContext.Current.Response.End();
843 }
844
845 /**//// <summary>
846 /// 获取网页table标签的内容
847 /// </summary>
848 /// <param name="input">html代码</param>
849 /// <returns></returns>
850 private static string getBodyContent( string input )
851 {
852 string pattern = @"<table.*?</table>";
853 Regex reg = new Regex( pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase );
854 Match mc = reg.Match( input );
855 string bodyContent = "";
856 if( mc.Success )
857 {
858 bodyContent = mc.Value;
859 }
860 return bodyContent;
861 }
862 #endregion
863
864 判断系统是否装excel#region 判断系统是否装excel
865 /**//// <summary>
866 /// 判断系统是否装excel
867 /// </summary>
868 /// <returns></returns>
869 public static bool IsInstallExcel()
870 {
871 RegistryKey machineKey = Registry.LocalMachine;
872 if( IsInstallExcelByVersion( "12.0", machineKey ) )
873 {
874 return true;
875 }
876 if( IsInstallExcelByVersion( "11.0", machineKey ) )
877 {
878 return true;
879 }
880 return false;
881 }
882
883 /**//// <summary>
884 /// 判断系统是否装某版本的excel
885 /// </summary>
886 /// <param name="strVersion">版本号</param>
887 /// <param name="machineKey"></param>
888 /// <returns></returns>
889 private static bool IsInstallExcelByVersion( string strVersion, RegistryKey machineKey )
890 {
891 try
892 {
893 RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Excel" ).OpenSubKey( "InstallRoot" );
894 if( installKey == null )
895 {
896 return false;
897 }
898 return true;
899 }
900 catch
901 {
902 return false;
903 }
904 }
905 #endregion
906
907 判断系统是否装word#region 判断系统是否装word
908 /**//// <summary>
909 /// 判断系统是否装word
910 /// </summary>
911 /// <returns></returns>
912 public static bool IsInstallWord()
913 {
914 RegistryKey machineKey = Registry.LocalMachine;
915 if( IsInstallExcelByVersion( "12.0", machineKey ) )
916 {
917 return true;
918 }
919 if( IsInstallExcelByVersion( "11.0", machineKey ) )
920 {
921 return true;
922 }
923 return false;
924 }
925
926 /**//// <summary>
927 /// 判断系统是否装某版本的word
928 /// </summary>
929 /// <param name="strVersion">版本号</param>
930 /// <param name="machineKey"></param>
931 /// <returns></returns>
932 private static bool IsInstallWordByVersion( string strVersion, RegistryKey machineKey )
933 {
934 try
935 {
936 RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Word" ).OpenSubKey( "InstallRoot" );
937 if( installKey == null )
938 {
939 return false;
940 }
941 return true;
942 }
943 catch
944 {
945 return false;
946 }
947 }
948 #endregion
949 }
950}
951