The first time you've recently used VSTO (Visual Studio Tools for Office), you've written a small program that automatically generates word reports, and it feels VSTO very difficult to use. The main is not familiar with the Office object model, do not understand the meaning of many classes, methods, attributes, Word inside a very simple operation but do not know how to find the corresponding classes and methods to achieve. There is no way to see VSTO's comments directly in VS, and it's inconvenient to check MSDN. Finally found a relatively quick way, in fact, VBA and VSTO use a set of object model, as long as the need to implement the operation of recording macro, control the VBA code is easy to write the corresponding C # program.
Here are a few small examples.
Enter caption: Inserts a section of text at the current cursor and sets it to Heading 1 style, centered
The macros recorded in VBA are as follows:
Selection.TypeText Text:="Test Title"
Selection.Style = ActiveDocument.Styles("Heading 1")
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
Selection.TypeParagraph
The corresponding C # code:
//因为set_Style()要求传ref object参数,所以不能直接传string
object style_Heading1 = "Heading 1";
WordApp = new ApplicationClass();
WordApp.Selection.TypeText("Test Title");
//设置样式
WordApp.Selection.ParagraphFormat.set_Style(ref style_Heading1);
//居中
WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
//换行
WordApp.Selection.TypeParagraph();
Insert a three row two column table, fill in the first row of the first column today's date, set the style, automatically adjusts to the content, remove the header row
Vba:
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=3, NumColumns:= _
2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
wdAutoFitFixed
With Selection.Tables(1)
If .Style <> "Table Grid" Then
.Style = "Table Grid"
End If
.ApplyStyleHeadingRows = True
.ApplyStyleLastRow = False
.ApplyStyleFirstColumn = True
.ApplyStyleLastColumn = False
.ApplyStyleRowBands = True
.ApplyStyleColumnBands = False
End With
Selection.Tables(1).Style = "Medium Shading 1 - Accent 5"
Selection.Tables(1).ApplyStyleHeadingRows = Not Selection.Tables(1). _
ApplyStyleHeadingRows
Selection.InsertDateTime DateTimeFormat:="M/d/yyyy", InsertAsField:=False, _
DateLanguage:=wdEnglishUS, CalendarType:=wdCalendarWestern, _
InsertAsFullWidth:=False
Selection.Tables(1).AutoFitBehavior (wdAutoFitContent)