使用 Word.Interop 时如何正确访问附加模板?

How to properly access AtttachedTemplate when using Word.Interop?

我正在尝试使用 Microsoft.Office.Interop.Word 库从我的 C# 应用程序创建 Microsoft Word 文档。我使用一个模板文件来保存几个构建块,并用它们搭建一个文档,如下所示:

using Word = Microsoft.Office.Interop.Word

Word.Application wdApplication = null;
dynamic wdDocument = null;

try {
  wdApplication = new Word.Application();
  wdDocument = wdApplication.Documents.Add(Properties.Settings.Default.Template);
  wdDocument.AttachedTemplate.BuildingBlockEntries("Agenda.Header").Insert(wdDocument.Paragraphs.Last().Range);
  // ...
} catch { }

这样一切正常。问题是因为我将 wdDocument 声明为 dynamic 我没有得到任何 IntelliSense 提示,否则会节省我很多时间和精力。

然而,当我尝试将 wdDocument 声明为 Word.Document 时,出现以下错误:

Error CS1545 Property, indexer, or event '_Document.AttachedTemplate' is not supported by the language; try directly calling accessor methods '_Document.get_AttachedTemplate()' or '_Document.set_AttachedTemplate(ref object)'

我也尝试将 wdDocument 声明为 Microsoft.Office.Tools.Word.Document,但这只会在 wdApplicationwdDocument.

之间引入类型转换错误

声明文档类型或访问存储在附加模板中的构建块的正确方法是什么?

非常感谢@mjwills 让我走上正轨。这是我用积木创建 Word 文档的最终代码:

using Word = Microsoft.Office.Interop.Word;

public class Agenda {
  public static void Create() {
    Word.Application wordApplication = null;
    Word.Document wdDocument = null;
    Word.Template wdTemplate = null;
    Word.BuildingBlock wdBuildingBlock = null;

    object paramBBCategory = "Agenda";
    object paramBBName = "Header";

    try {
      wordApplication = new Word.Application();
      wdDocument = wordApplication.Documents.Add(Properties.Settings.Default.Template);
      wdTemplate = (Word.Template)wdDocument.get_AttachedTemplate();

      wdBuildingBlock = wdTemplate
        .BuildingBlockTypes.Item(Word.WdBuildingBlockTypes.wdTypeQuickParts)
        .Categories.Item(ref paramBBCategory)
        .BuildingBlocks.Item(ref paramBBName);
      wordBuildingBlock.Insert(wdDocument.Paragraphs.Last.Range);
    } catch { }
  }
}

请参阅 MSDN 上的这篇精彩文章以供参考:Retrieving Custom Building Blocks from Templates in Word 2007