使用Word.Interop时,如何正确访问AttTachedTemplate



我正在尝试使用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时,我会收到以下错误:

错误CS1545属性,索引或事件" _document.attachedtemplate"不受语言支持;尝试直接调用访问者方法'_document.get_attachedtemplate()'或'_document.set_attachedtemplate(ref object)'

我还尝试将wdDocument称为Microsoft.Office.Tools.Word.Document,但这仅在wdApplication A a wdDocument之间引入类型转换错误。

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

非常感谢@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上的这篇很棒的文章,以获取参考:从Word 2007中的模板中检索自定义构建块

最新更新