博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c# word 操作
阅读量:4623 次
发布时间:2019-06-09

本文共 45895 字,大约阅读时间需要 152 分钟。

 

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

 

转载于:https://www.cnblogs.com/endv/p/5199649.html

你可能感兴趣的文章
Windows平台flex+gcc词法分析实验工具包
查看>>
3.Python基础 序列sequence
查看>>
Chapter 4 Syntax Analysis
查看>>
vi/vim使用
查看>>
讨论Spring整合Mybatis时一级缓存失效得问题
查看>>
Maven私服配置Setting和Pom文件
查看>>
Linux搭建Nexus3.X构建maven私服
查看>>
NPOI 操作Excel
查看>>
MySql【Error笔记】
查看>>
vue入门
查看>>
JS线程Web worker
查看>>
Flex的动画效果与变换!(三)(完)
查看>>
mysql常见错误码
查看>>
Openresty 与 Tengine
查看>>
使用XV-11激光雷达做hector_slam
查看>>
布局技巧4:使用ViewStub
查看>>
学习记事
查看>>
java 子类重写父类的方法应注意的问题
查看>>
[LevelDB] LevelDB理论基础
查看>>
【codecombat】 试玩全攻略 第一关kithguard地牢
查看>>