【问题标题】:How to properly access AtttachedTemplate when using Word.Interop?使用 Word.Interop 时如何正确访问附加模板?
【发布时间】:2018-05-16 09:41:08
【问题描述】:

我正在尝试使用 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 和wdDocument 之间引入类型转换错误。

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

【问题讨论】:

  • @mjwills 我看过那个链接,但不幸的是它没有帮助。它是关于设置附加的模板,而不是访问它的属性。还是谢谢!
  • 所以get_AttachedTemplate 不适合你?
  • 你能分享一下你在尝试使用get_AttachedTemplate()时遇到的编译器错误吗?
  • @mjwills 当然。当我尝试使用 get_AttachedTemplate like this 时,我在第 13 行收到以下错误:CS1955 Error Non-invocable member 'Template.BuildingBlockEntries' cannot be used like a method.。
  • @mjwills 感谢您的时间和精力!

标签: c# ms-word interop


【解决方案1】:

非常感谢@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多