首次使用 VSTO (Visual Studio Tools For Office) 撰寫自動產生 Word 報告程式,發現 VSTO 難用,主因 Office 物件模型不熟,類別/方法/屬性含義難理解,Word 簡單操作卻難對應程式碼。VS 無法直接看 VSTO 註解,查 MSDN 不便。後發現技巧:VBA 與 VSTO 共用物件模型,將操作錄製為巨集,參考 VBA 代碼即可輕鬆撰寫 C# 程式。
VBA 巨集:
Selection.TypeText Text:="Test Title"
Selection.Style = ActiveDocument.Styles("Heading 1")
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
Selection.TypeParagraph
對應 C# 代碼:
object style_Heading1 = "Heading 1";
WordApp = new ApplicationClass();
WordApp.Selection.TypeText("Test Title");
WordApp.Selection.ParagraphFormat.set_Style(ref style_Heading1); // 需傳 ref object
WordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
WordApp.Selection.TypeParagraph();
VBA:
ActiveDocument.Tables.Add Range:=Selection.Range, NumRows:=3, NumColumns:=2, ...
With Selection.Tables(1)
If .Style <> "Table Grid" Then .Style = "Table Grid"
.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", ...
Selection.Tables(1).AutoFitBehavior (wdAutoFitContent)
對應 C# 代碼需逐行轉換,利用 VBA 巨集作為參考大幅降低學習曲線。