本文中用C#來操作Word,包括:
創建Word;
插入文字,選擇文字,編輯文字的字號、粗細、顏色、下划線等;
設置段落的首行縮進、行距;
設置頁面頁邊距和紙張大小;
設置頁眉、頁碼;
插入圖片,設置圖片寬高以及給圖片添加標題;
插入表格,格式化表格,往表格中插入數據;
保存Word,打印Word;
重新打開Word等。
Visual studio版本:Visual Studio 2012(2010應該也可以)
准備工作:
/*
1. 添加引用COM里面的 Microsoft Word 12.0 Object. Library 引用(12.0表示Word 2007版本)
2. 導命名空間
using MSWord =Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
3. 把引用中的Microsoft.Office.Interop.Word的“屬性”中的嵌入互操作設為False
*/
以下是全部代碼:(代碼有點長,但請不要有壓力,直接復制進去就能直接成功運行)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.InteropServices; 5 using System.Text; 6 using MSWord = Microsoft.Office.Interop.Word; 7 using System.IO; 8 using System.Reflection; 9 10 namespace Console_WordSkill_All 11 { 12 class Program 13 { 14 static void Main(string[] args) 15 { 16 object path; //文件路徑變量 17 string strContent; //文本內容變量 18 MSWord.Application wordApp; //Word應用程序變量 19 MSWord.Document wordDoc; //Word文檔變量 20 21 path = Environment.CurrentDirectory + "\\MyWord_Print.doc"; 22 wordApp = new MSWord.ApplicationClass(); //初始化 23 24 wordApp.Visible = true;//使文檔可見 25 26 //如果已存在,則刪除 27 if (File.Exists((string)path)) 28 { 29 File.Delete((string)path); 30 } 31 32 //由於使用的是COM庫,因此有許多變量需要用Missing.Value代替 33 Object Nothing = Missing.Value; 34 wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); 35 36 #region 頁面設置、頁眉圖片和文字設置,最后跳出頁眉設置 37 38 //頁面設置 39 wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;//設置紙張樣式為A4紙 40 wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientPortrait;//排列方式為垂直方向 41 wordDoc.PageSetup.TopMargin = 57.0f; 42 wordDoc.PageSetup.BottomMargin = 57.0f; 43 wordDoc.PageSetup.LeftMargin = 57.0f; 44 wordDoc.PageSetup.RightMargin = 57.0f; 45 wordDoc.PageSetup.HeaderDistance = 30.0f;//頁眉位置 46 47 //設置頁眉 48 wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;//普通視圖(即頁面視圖)樣式 49 wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekPrimaryHeader;//進入頁眉設置,其中頁眉邊距在頁面設置中已完成 50 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;//頁眉中的文字右對齊 51 52 53 //插入頁眉圖片(測試結果圖片未插入成功) 54 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; 55 string headerfile = @"C:\Users\xiahui\Desktop\OficeProgram\3.jpg"; 56 MSWord.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing); 57 shape1.Height = 5;//強行設置貌似無效,圖片沒有按設置的縮放——圖片的比例並沒有改變。 58 shape1.Width = 20; 59 wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(" 文檔頁眉");//在頁眉的圖片后面追加幾個字 60 61 //去掉頁眉的橫線 62 wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleNone; 63 wordApp.ActiveWindow.ActivePane.Selection.Borders[MSWord.WdBorderType.wdBorderBottom].Visible = false; 64 wordApp.ActiveWindow.ActivePane.View.SeekView = MSWord.WdSeekView.wdSeekMainDocument;//退出頁眉設置 65 #endregion 66 67 #region 頁碼設置並添加頁碼 68 69 //為當前頁添加頁碼 70 MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//獲取當前頁的號碼 71 pns.NumberStyle = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;//設置頁碼的風格,是Dash形還是圓形的 72 pns.HeadingLevelForChapter = 0; 73 pns.IncludeChapterNumber = false; 74 pns.RestartNumberingAtSection = false; 75 pns.StartingNumber = 0; //開始頁頁碼? 76 object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter;//將號碼設置在中間 77 object first = true; 78 wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first); 79 80 #endregion 81 82 #region 行間距與縮進、文本字體、字號、加粗、斜體、顏色、下划線、下划線顏色設置 83 84 wordApp.Selection.ParagraphFormat.LineSpacing = 16f;//設置文檔的行間距 85 wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行縮進的長度 86 //寫入普通文本 87 strContent = "我是普通文本\n"; 88 wordDoc.Paragraphs.Last.Range.Text = strContent; 89 90 wordDoc.Paragraphs.Last.Range.Text = "我再加一行試試,這里不加'\\n'"; 91 //直接添加段,不是覆蓋( += ) 92 wordDoc.Paragraphs.Last.Range.Text += "不會覆蓋的,"; 93 94 //添加在此段的文字后面,不是新段落 95 wordDoc.Paragraphs.Last.Range.InsertAfter("這是后面的內容\n"); 96 97 //將文檔的前4個字替換成"哥是替換文字",並將其顏色設為紅色 98 object start = 0; 99 object end = 4; 100 MSWord.Range rang = wordDoc.Range(ref start, ref end); 101 rang.Font.Color = MSWord.WdColor.wdColorRed; 102 rang.Text = "哥是替換文字"; 103 wordDoc.Range(ref start, ref end); 104 105 //寫入黑體文本 106 object unite = MSWord.WdUnits.wdStory; 107 wordApp.Selection.EndKey(ref unite, ref Nothing);//將光標移到文本末尾 108 wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行縮進的長度 109 strContent = "這是黑體文本\n"; 110 wordDoc.Paragraphs.Last.Range.Font.Name = "黑體"; 111 wordDoc.Paragraphs.Last.Range.Text = strContent; 112 113 //寫入加粗文本 114 strContent = "這是粗體文本\n"; // 115 wordApp.Selection.EndKey(ref unite, ref Nothing);//這一句不加,有時候好像也不出問題,不過還是加了安全 116 wordDoc.Paragraphs.Last.Range.Font.Bold = 1; 117 wordDoc.Paragraphs.Last.Range.Text = strContent; 118 119 //寫入15號字體文本 120 strContent = "我這個文本的字號是15號,而且是宋體\n"; 121 wordApp.Selection.EndKey(ref unite, ref Nothing); 122 wordDoc.Paragraphs.Last.Range.Font.Size = 15; 123 wordDoc.Paragraphs.Last.Range.Font.Name = "宋體"; 124 wordDoc.Paragraphs.Last.Range.Text = strContent; 125 126 //寫入斜體文本 127 strContent = "我是斜體字文本\n"; 128 wordApp.Selection.EndKey(ref unite, ref Nothing); 129 wordDoc.Paragraphs.Last.Range.Font.Italic = 1; 130 wordDoc.Paragraphs.Last.Range.Text = strContent; 131 132 //寫入藍色文本 133 strContent = "我是藍色的文本\n"; 134 wordApp.Selection.EndKey(ref unite, ref Nothing); 135 wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue; 136 wordDoc.Paragraphs.Last.Range.Text = strContent; 137 138 //寫入下划線文本 139 strContent = "我是下划線文本\n"; 140 wordApp.Selection.EndKey(ref unite, ref Nothing); 141 wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick; 142 wordDoc.Paragraphs.Last.Range.Text = strContent; 143 144 //寫入紅色下畫線文本 145 strContent = "我是點線下划線,並且下划線是紅色的\n"; 146 wordApp.Selection.EndKey(ref unite, ref Nothing); 147 wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineDottedHeavy; 148 wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed; 149 wordDoc.Paragraphs.Last.Range.Text = strContent; 150 151 //取消下划線,並且將字號調整為12號 152 strContent = "我他媽不要下划線了,並且設置字號為12號,黑色不要斜體\n"; 153 wordApp.Selection.EndKey(ref unite, ref Nothing); 154 wordDoc.Paragraphs.Last.Range.Font.Size = 12; 155 wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineNone; 156 wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack; 157 wordDoc.Paragraphs.Last.Range.Font.Italic = 0; 158 wordDoc.Paragraphs.Last.Range.Text = strContent; 159 160 161 #endregion 162 163 164 #region 插入圖片、居中顯示,設置圖片的絕對尺寸和縮放尺寸,並給圖片添加標題 165 166 wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾 167 //圖片文件的路徑 168 string filename = Environment.CurrentDirectory + "\\6.jpg"; 169 //要向Word文檔中插入圖片的位置 170 Object range = wordDoc.Paragraphs.Last.Range; 171 //定義該插入的圖片是否為外部鏈接 172 Object linkToFile = false; //默認,這里貌似設置為bool類型更清晰一些 173 //定義要插入的圖片是否隨Word文檔一起保存 174 Object saveWithDocument = true; //默認 175 //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入圖片 176 wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range); 177 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中顯示圖片 178 179 //設置圖片寬高的絕對大小 180 181 //wordDoc.InlineShapes[1].Width = 200; 182 //wordDoc.InlineShapes[1].Height = 150; 183 //按比例縮放大小 184 185 wordDoc.InlineShapes[1].ScaleWidth = 20;//縮小到20% ? 186 wordDoc.InlineShapes[1].ScaleHeight = 20; 187 188 //在圖下方居中添加圖片標題 189 190 wordDoc.Content.InsertAfter("\n");//這一句與下一句的順序不能顛倒,原因還沒搞透 191 wordApp.Selection.EndKey(ref unite, ref Nothing); 192 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; 193 wordApp.Selection.Font.Size = 10;//字體大小 194 wordApp.Selection.TypeText("圖1 測試圖片\n"); 195 196 #endregion 197 198 #region 添加表格、填充數據、設置表格行列寬高、合並單元格、添加表頭斜線、給單元格添加圖片 199 wordDoc.Content.InsertAfter("\n");//這一句與下一句的順序不能顛倒,原因還沒搞透 200 wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾 201 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft; 202 //object WdLine2 = MSWord.WdUnits.wdLine;//換一行; 203 //wordApp.Selection.MoveDown(ref WdLine2, 6, ref Nothing);//向下跨15行輸入表格,這樣表格就在文字下方了,不過這是非主流的方法 204 205 //設置表格的行數和列數 206 int tableRow = 6; 207 int tableColumn = 6; 208 209 //定義一個Word中的表格對象 210 MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, 211 tableRow, tableColumn, ref Nothing, ref Nothing); 212 213 //默認創建的表格沒有邊框,這里修改其屬性,使得創建的表格帶有邊框 214 table.Borders.Enable = 1;//這個值可以設置得很大,例如5、13等等 215 216 //表格的索引是從1開始的。 217 wordDoc.Tables[1].Cell(1, 1).Range.Text = "列\n行"; 218 for (int i = 1; i < tableRow; i++) 219 { 220 for (int j = 1; j < tableColumn; j++) 221 { 222 if (i == 1) 223 { 224 table.Cell(i, j + 1).Range.Text = "Column " + j;//填充每列的標題 225 } 226 if (j == 1) 227 { 228 table.Cell(i + 1, j).Range.Text = "Row " + i; //填充每行的標題 229 } 230 table.Cell(i + 1, j + 1).Range.Text = i + "行 " + j + "列"; //填充表格的各個小格子 231 } 232 } 233 234 235 //添加行 236 table.Rows.Add(ref Nothing); 237 table.Rows[tableRow + 1].Height = 35;//設置新增加的這行表格的高度 238 //向新添加的行的單元格中添加圖片 239 string FileName = Environment.CurrentDirectory + "\\6.jpg";//圖片所在路徑 240 object LinkToFile = false; 241 object SaveWithDocument = true; 242 object Anchor = table.Cell(tableRow + 1, tableColumn).Range;//選中要添加圖片的單元格 243 wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); 244 245 //由於是本文檔的第2張圖,所以這里是InlineShapes[2] 246 wordDoc.Application.ActiveDocument.InlineShapes[2].Width = 50;//圖片寬度 247 wordDoc.Application.ActiveDocument.InlineShapes[2].Height = 35;//圖片高度 248 249 // 將圖片設置為四周環繞型 250 MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[2].ConvertToShape(); 251 s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare; 252 253 254 //設置table樣式 255 table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//高度規則是:行高有最低值下限? 256 table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));// 257 258 table.Range.Font.Size = 10.5F; 259 table.Range.Font.Bold = 0; 260 261 table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//表格文本居中 262 table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;//文本垂直貼到底部 263 //設置table邊框樣式 264 table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;//表格外框是雙線 265 table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格內框是單線 266 267 table.Rows[1].Range.Font.Bold = 1;//加粗 268 table.Rows[1].Range.Font.Size = 12F; 269 table.Cell(1, 1).Range.Font.Size = 10.5F; 270 wordApp.Selection.Cells.Height = 30;//所有單元格的高度 271 272 //除第一行外,其他行的行高都設置為20 273 for (int i = 2; i <= tableRow; i++) 274 { 275 table.Rows[i].Height = 20; 276 } 277 278 //將表格左上角的單元格里的文字(“行” 和 “列”)居右 279 table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight; 280 //將表格左上角的單元格里面下面的“列”字移到左邊,相比上一行就是將ParagraphFormat改成了Paragraphs[2].Format 281 table.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft; 282 283 table.Columns[1].Width = 50;//將第 1列寬度設置為50 284 285 //將其他列的寬度都設置為75 286 for (int i = 2; i <= tableColumn; i++) 287 { 288 table.Columns[i].Width = 75; 289 } 290 291 292 //添加表頭斜線,並設置表頭的樣式 293 table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Visible = true; 294 table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Color = MSWord.WdColor.wdColorRed; 295 table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].LineWidth = MSWord.WdLineWidth.wdLineWidth150pt; 296 297 //合並單元格 298 table.Cell(4, 4).Merge(table.Cell(4, 5));//橫向合並 299 300 table.Cell(2, 3).Merge(table.Cell(4, 3));//縱向合並,合並(2,3),(3,3),(4,3) 301 302 #endregion 303 304 wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾 305 306 wordDoc.Content.InsertAfter("\n"); 307 wordDoc.Content.InsertAfter("就寫這么多,算了吧!2016.09.27"); 308 309 310 311 //WdSaveFormat為Word 2003文檔的保存格式 312 object format = MSWord.WdSaveFormat.wdFormatDocument;// office 2007就是wdFormatDocumentDefault 313 //將wordDoc文檔對象的內容保存為DOCX文檔 314 wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); 315 //關閉wordDoc文檔對象 316 317 //看是不是要打印 318 //wordDoc.PrintOut(); 319 320 321 322 wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); 323 //關閉wordApp組件對象 324 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); 325 Console.WriteLine(path + " 創建完畢!"); 326 Console.ReadKey(); 327 328 329 //我還要打開這個文檔玩玩 330 MSWord.Application app = new MSWord.Application(); 331 MSWord.Document doc = null; 332 try 333 { 334 335 object unknow = Type.Missing; 336 app.Visible = true; 337 string str = Environment.CurrentDirectory + "\\MyWord_Print.doc"; 338 object file = str; 339 doc = app.Documents.Open(ref file, 340 ref unknow, ref unknow, ref unknow, ref unknow, 341 ref unknow, ref unknow, ref unknow, ref unknow, 342 ref unknow, ref unknow, ref unknow, ref unknow, 343 ref unknow, ref unknow, ref unknow); 344 string temp = doc.Paragraphs[1].Range.Text.Trim(); 345 Console.WriteLine("你他媽輸出temp干嘛?"); 346 } 347 catch (Exception ex) 348 { 349 Console.WriteLine(ex.Message); 350 } 351 wordDoc = doc; 352 wordDoc.Paragraphs.Last.Range.Text += "我真的不打算再寫了,就寫這么多吧"; 353 354 Console.ReadKey(); 355 } 356 357 } 358 }
生成編輯的Word內容如下圖所示:
word文檔工程變量的屬性 //合並單元格 table.Cell(2, 2).Merge(table.Cell(2, 3)); //單元格分離 object Rownum = 2; object Columnnum = 2; table.Cell(2, 2).Split(ref Rownum, ref Columnnum); //單元格對齊方式 WApp.Selection.Cells.VerticalAlignment =Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //插入表行 table.Rows.Add(ref missing); //分頁 object ib = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak; WApp.Selection.InsertBreak(ref ib); //換行 WApp.Selection.TypeParagraph(); 二、word文檔設置 WApp.ActiveDocument.PageSetup.LineNumbering.Active =0;//行編號 WApp.ActiveDocument.PageSetup.Orientation =Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//頁面方向 WApp.ActiveDocument.PageSetup.TopMargin =WApp.CentimetersToPoints(float.Parse("2.54"));//上頁邊距 WApp.ActiveDocument.PageSetup.BottomMargin = WApp.CentimetersToPoints(float.Parse("2.54"));//下頁邊距 WApp.ActiveDocument.PageSetup.LeftMargin = WApp.CentimetersToPoints(float.Parse("3.17"));//左頁邊距 WApp.ActiveDocument.PageSetup.RightMargin = WApp.CentimetersToPoints(float.Parse("3.17"));//右頁邊距 WApp.ActiveDocument.PageSetup.Gutter = WApp.CentimetersToPoints(float.Parse("0"));//裝訂線位置 WApp.ActiveDocument.PageSetup.HeaderDistance = WApp.CentimetersToPoints(float.Parse("1.5"));//頁眉 WApp.ActiveDocument.PageSetup.FooterDistance = WApp.CentimetersToPoints(float.Parse("1.75"));//頁腳 WApp.ActiveDocument.PageSetup.PageWidth = WApp.CentimetersToPoints(float.Parse("21"));//紙張寬度 WApp.ActiveDocument.PageSetup.PageHeight = WApp.CentimetersToPoints(float.Parse("29.7"));//紙張高度 WApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//紙張來源 WApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//紙張來源 WApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//節的起始位置:新建頁 WApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//頁眉頁腳-奇偶頁不同 WApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//頁眉頁腳-首頁不同 WApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//頁面垂直對齊方式 WApp.ActiveDocument.PageSetup.SuppressEndnotes =0;//不隱藏尾注 WApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不設置首頁的內外邊距 WApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不雙面打印 WApp.ActiveDocument.PageSetup.BookFoldPrinting =false;//不設置手動雙面正面打印 WApp.ActiveDocument.PageSetup.BookFoldRevPrinting =false;//不設置手動雙面背面打印 WApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默認份數 WApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//裝訂線位於左側 WApp.ActiveDocument.PageSetup.LinesPage = 40;//默認頁行數量 WApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式為“只指定行網格” 三、光標移動 //移動光標 //光標下移3行 上移3行 object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine; object count = 3; WApp.Selection.MoveEnd(ref unit,ref count); WApp.Selection.MoveUp(ref unit, ref count, ref missing); //Microsoft.Office.Interop.Word.WdUnits說明 //wdCell A cell. //wdCharacter A character. //wdCharacterFormatting Character formatting. //wdColumn A column. //wdItem The selected item. //wdLine A line. //行 //wdParagraph A paragraph. //wdParagraphFormatting Paragraph formatting. //wdRow A row. //wdScreen The screen dimensions. //wdSection A section. //wdSentence A sentence. //wdStory A story. //wdTable A table. //wdWindow A window. //wdWord A word. //錄制的vb宏 // ,移動光標至當前行首 // Selection.HomeKey unit:=wdLine // '移動光標至當前行尾 // Selection.EndKey unit:=wdLine // '選擇從光標至當前行首的內容 // Selection.HomeKey unit:=wdLine, Extend:=wdExtend // '選擇從光標至當前行尾的內容 // Selection.EndKey unit:=wdLine, Extend:=wdExtend // '選擇當前行 // Selection.HomeKey unit:=wdLine // Selection.EndKey unit:=wdLine, Extend:=wdExtend // '移動光標至文檔開始 // Selection.HomeKey unit:=wdStory // '移動光標至文檔結尾 // Selection.EndKey unit:=wdStory // '選擇從光標至文檔開始的內容 // Selection.HomeKey unit:=wdStory, Extend:=wdExtend // '選擇從光標至文檔結尾的內容 // Selection.EndKey unit:=wdStory, Extend:=wdExtend // '選擇文檔全部內容(從WholeStory可猜出Story應是當前文檔的意思) // Selection.WholeStory // '移動光標至當前段落的開始 // Selection.MoveUp unit:=wdParagraph // '移動光標至當前段落的結尾 // Selection.MoveDown unit:=wdParagraph // '選擇從光標至當前段落開始的內容 // Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend // '選擇從光標至當前段落結尾的內容 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend // '選擇光標所在段落的內容 // Selection.MoveUp unit:=wdParagraph // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend // '顯示選擇區的開始與結束的位置,注意:文檔第1個字符的位置是0 // MsgBox ("第" & Selection.Start & "個字符至第" & Selection.End & "個字符") // '刪除當前行 // Selection.HomeKey unit:=wdLine // Selection.EndKey unit:=wdLine, Extend:=wdExtend // Selection.Delete // '刪除當前段落 // Selection.MoveUp unit:=wdParagraph // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend // Selection.Delete //表格的光標移動 //光標到當前光標所在表格的地單元格 WApp.Selection.Tables[1].Cell(1, 1).Select(); //unit對象定義 object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式 object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;/**////extend對光標移動區域進行擴展選擇 object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文檔行方式,可以看成表格一行.不過和wdRow有區別 object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,對於表格可以選擇到表格行后的換車符,對於跨行合並的行選擇,我能找到的最簡單方式 object count=1;//光標移動量 下面代碼演示對於存在合並單元格的選擇操作.合並單元格的選擇問題一直是word的bug.部分object對象參照上面代碼 上面這個是表格合並樣式.要如何才能選擇2行標題欄尼.看下面代碼 //定位到表格第1單元格 WApp.Selection.Tables[1].Cell(1, 1).Select(); //定位到第1個單元格第1個字符前 WApp.Selection.HomeKey(ref unith, ref missing); //擴展到行尾,選擇表第1行 WApp.Selection.EndKey(ref unith, ref extend); //定義表格標題的行數量,titlerow為參數 object strtitlerow=titlerow-1; //移動光標選擇第1行的末尾段落標記 WApp.Selection.MoveDown(ref unitp, ref count, ref extend); //選擇下一行,因為合並的原因,如表格標題最后列是合並,只選擇了2行的部分 WApp.Selection.MoveDown(ref unitu, ref strtitlerow, ref extend); //擴展到該行的末端,保證合並行能全部選擇到 WApp.Selection.EndKey(ref unith, ref extend); //復制選擇內容到剪貼板 WApp.Selection.Copy(); //下面是移動光標到任何位置並粘貼內容.我程序中目的是到表格換頁的時候自動插入下一頁的表頭. WApp.Selection.Tables[1].Cell(System.Convert.ToInt32(strRownum), 1).Select(); WApp.Selection.HomeKey(ref unith, ref missing); WApp.Selection.Paste(); 四、段落格式設定 //段落格式設定 WApp.Selection.ParagraphFormat.LeftIndent = WApp.CentimetersToPoints(float.Parse("0"));//左縮進 WApp.Selection.ParagraphFormat.RightIndent = WApp.CentimetersToPoints(float.Parse("0"));//右縮進 WApp.Selection.ParagraphFormat.SpaceBefore =float.Parse("0");//段前間距 WApp.Selection.ParagraphFormat.SpaceBeforeAuto =0;// WApp.Selection.ParagraphFormat.SpaceAfter = float.Parse("0");//段后間距 WApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;// WApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//單倍行距 WApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端對齊 WApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制 WApp.Selection.ParagraphFormat.KeepWithNext = 0;//與下段同頁 WApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分頁 WApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分頁 WApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行號 WApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字 WApp.Selection.ParagraphFormat.FirstLineIndent = WApp.CentimetersToPoints(float.Parse("0"));//首行縮進 WApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText; WApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse("0"); WApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse("0"); WApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse("0"); WApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse("0"); WApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse("0"); WApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1; WApp.Selection.ParagraphFormat.DisableLineHeightGrid =0; WApp.Selection.ParagraphFormat.FarEastLineBreakControl =1; WApp.Selection.ParagraphFormat.WordWrap = 1; WApp.Selection.ParagraphFormat.HangingPunctuation = 1; WApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0; WApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1; WApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1; WApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto; 五、字體格式設定 //字體格式設定 WApp.Selection.Font.NameFarEast = "華文中宋"; WApp.Selection.Font.NameAscii = "Times New Roman"; WApp.Selection.Font.NameOther = "Times New Roman"; WApp.Selection.Font.Name = "宋體"; WApp.Selection.Font.Size = float.Parse("14"); WApp.Selection.Font.Bold = 0; WApp.Selection.Font.Italic = 0; WApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone; WApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; WApp.Selection.Font.StrikeThrough =0;//刪除線 WApp.Selection.Font.DoubleStrikeThrough = 0;//雙刪除線 WApp.Selection.Font.Outline =0;//空心 WApp.Selection.Font.Emboss = 0;//陽文 WApp.Selection.Font.Shadow = 0;//陰影 WApp.Selection.Font.Hidden = 0;//隱藏文字 WApp.Selection.Font.SmallCaps = 0;//小型大寫字母 WApp.Selection.Font.AllCaps = 0;//全部大寫字母 WApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; WApp.Selection.Font.Engrave = 0;//陰文 WApp.Selection.Font.Superscript = 0;//上標 WApp.Selection.Font.Subscript = 0;//下標 WApp.Selection.Font.Spacing = float.Parse("0");//字符間距 WApp.Selection.Font.Scaling = 100;//字符縮放 WApp.Selection.Font.Position = 0;//位置 WApp.Selection.Font.Kerning = float.Parse("1");//字體間距調整 WApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果 WApp.Selection.Font.DisableCharacterSpaceGrid =false; WApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone; 六、終於找到了獲取光標位置的東東。那里找到的忘了,感謝提供的老大。放到這里供大家參考。 有了這個和上面內容,相信大家對word文檔的控制應該到了隨心所欲的地步,爽啊 獲取的c#語法 //get_Information Selection.get_Information(WdInformation.wdActiveEndPageNumber) //關於行號-頁號-列號-位置 //information 屬性 //返回有關指定的所選內容或區域的信息。variant 類型,只讀。 //expression.information(type) //expression 必需。該表達式返回一個 range 或 selection 對象。 //type long 類型,必需。需要返回的信息。可取下列 wdinformation 常量之一: //wdactiveendadjustedpagenumber 返回頁碼,在該頁中包含指定的所選內容或區域的活動結尾。如果設置了一個起始頁碼,並對頁碼進行了手工調整,則返回調整過的頁碼。 //wdactiveendpagenumber 返回頁碼,在該頁中包含指定的所選內容或區域的活動結尾,頁碼從文檔的開頭開始計算而不考慮對頁碼的任何手工調整。 //wdactiveendsectionnumber 返回節號,在該節中包含了指定的所選內容或區域的活動結尾。 //wdatendofrowmarker 如果指定的所選內容或區域位於表格的行結尾標記處,則本參數返回 true。 //wdcapslock 如果大寫字母鎖定模式有效,則本參數返回 true。 //wdendofrangecolumnnumber 返回表格列號,在該表格列中包含了指定的所選內容或區域的活動結尾。 //wdendofrangerownumber 返回表格行號,在該表格行包含了指定的所選內容或區域的活動結尾。 //wdfirstcharactercolumnnumber 返回指定的所選內容或區域中第一個字符的位置。如果所選內容或區域是折疊的,則返回所選內容或區域右側緊接着的字符編號。 //wdfirstcharacterlinenumber 返回所選內容中第一個字符的行號。如果 pagination 屬性為 false,或 draft 屬性為 true,則返回 - 1。 //wdframeisselected 如果所選內容或區域是一個完整的圖文框文本框,則本參數返回 true。 //wdheaderfootertype 返回一個值,該值表明包含了指定的所選內容或區域的頁眉或頁腳的類型,如下表所示。 值 頁眉或頁腳的類型 //- 1 無 //0 偶數頁頁眉 //1 奇數頁頁眉 //2 偶數頁頁腳 //3 奇數頁頁腳 //4 第一個頁眉 //5 第一個頁腳 //wdhorizontalpositionrelativetopage 返回指定的所選內容或區域的水平位置。該位置是所選內容或區域的左邊與頁面的左邊之間的距離,以磅為單位。如果所選內容或區域不可見,則返回 - 1。 //wdhorizontalpositionrelativetotextboundary 返回指定的所選內容或區域相對於周圍最近的正文邊界的左邊的水平位置,以磅為單位。如果所選內容或區域沒有顯示在當前屏幕,則本參數返回 - 1。 //wdinclipboard 有關此常量的詳細內容,請參閱 microsoft office 98 macintosh 版的語言參考幫助。 //wdincommentpane 如果指定的所選內容或區域位於批注窗格,則返回 true。 //wdinendnote 如果指定的所選內容或區域位於頁面視圖的尾注區內,或者位於普通視圖的尾注窗格中,則本參數返回 true。 //wdinfootnote 如果指定的所選內容或區域位於頁面視圖的腳注區內,或者位於普通視圖的腳注窗格中,則本參數返回 true。 //wdinfootnoteendnotepane 如果指定的所選內容或區域位於頁面視圖的腳注或尾注區內,或者位於普通視圖的腳注或尾注窗格中,則本參數返回 true。詳細內容,請參閱前面的 wdinfootnote 和 wdinendnote 的說明。 //wdinheaderfooter 如果指定的所選內容或區域位於頁眉或頁腳窗格中,或者位於頁面視圖的頁眉或頁腳中,則本參數返回 true。 //wdinmasterdocument 如果指定的所選內容或區域位於主控文檔中,則本參數返回 true。 //wdinwordmail 返回一個值,該值表明了所選內容或區域的的位置,如下表所示。值 位置 //0 所選內容或區域不在一條電子郵件消息中。 //1 所選內容或區域位於正在發送的電子郵件中。 //2 所選內容或區域位於正在閱讀的電子郵件中。 //wdmaximumnumberofcolumns 返回所選內容或區域中任何行的最大表格列數。 //wdmaximumnumberofrows 返回指定的所選內容或區域中表格的最大行數。 //wdnumberofpagesindocument 返回與所選內容或區域相關聯的文檔的頁數。 //wdnumlock 如果 num lock 有效,則本參數返回 true。 //wdovertype 如果改寫模式有效,則本參數返回 true。可用 overtype 屬性改變改寫模式的狀態。 //wdreferenceoftype 返回一個值,該值表明所選內容相對於腳注、尾注或批注引用的位置,如下表所示。 值 描述 //— 1 所選內容或區域包含、但不只限定於腳注、尾注或批注引用中。 //0 所選內容或區域不在腳注、尾注或批注引用之前。 //1 所選內容或區域位於腳注引用之前。 //2 所選內容或區域位於尾注引用之前。 //3 所選內容或區域位於批注引用之前。 //wdrevisionmarking 如果修訂功能處於活動狀態,則本參數返回 true。 //wdselectionmode 返回一個值,該值表明當前的選定模式,如下表所示。 值 選定模式 //0 常規選定 //1 擴展選定 //2 列選定 //wdstartofrangecolumnnumber 返回所選內容或區域的起點所在的表格的列號。 //wdstartofrangerownumber 返回所選內容或區域的起點所在的表格的行號。 //wdverticalpositionrelativetopage 返回所選內容或區域的垂直位置,即所選內容的上邊與頁面的上邊之間的距離,以磅為單位。如果所選內容或區域沒有顯示在屏幕上,則本參數返回 - 1。 //wdverticalpositionrelativetotextboundary 返回所選內容或區域相對於周圍最近的正文邊界的上邊的垂直位置,以磅為單位。如果所選內容或區域沒有顯示在屏幕上,則本參數返回 - 1。 //wdwithintable 如果所選內容位於一個表格中,則本參數返回 true。 //wdzoompercentage 返回由 percentage 屬性設置的當前的放大百分比。
參考資料:
http://blog.csdn.net/ruby97/article/details/7406806
http://blog.csdn.net/yhrun/article/details/7674540
http://www.cnblogs.com/eye-like/p/4121219.html
http://www.cnblogs.com/knowledgesea/archive/2013/05/24/3095376.html
http://www.cnblogs.com/shi2172843/p/5848116.html
https://msdn.microsoft.com/en-us/library/bb257531(v=office.12).aspx
http://wenku.baidu.com/view/80ec0a6c1eb91a37f1115cab.html?from=search
---------------------
作者:xh6300
來源:CNBLOGS
原文:https://www.cnblogs.com/xh6300/p/5915717.html
版權聲明:本文為作者原創文章,轉載請附上博文鏈接!