首页 > 解决方案 > 用于插入另一个文档的 Google Docs 脚本

问题描述

我正在寻找使用自定义菜单来插入另一个整个文档。

这个想法是我创建了一组谷歌文档,其中每个都有自定义表格,然后用户可以从菜单中运行一个脚本来插入表格/模板。

创建菜单很容易(.createMenu)并添加我可以做的菜单项。但是,如何创建一个脚本来复制整个另一个谷歌文档(基于 doc.id)并插入到我当前的文档中?

标签: google-apps-scriptgoogle-docs

解决方案


您可以通过获取一个文档的正文并将其子元素附加到当前文档来做到这一点

function appendTemplate(templateID) {

  var thisDoc = DocumentApp.getActiveDocument();
  var thisBody = thisDoc.getBody();

  var templateDoc = DocumentApp.openById(templateID); //Pass in id of doc to be used as a template.
  var templateBody = templateDoc.getBody();

  for(var i=0; i<templateBody.getNumChildren();i++){ //run through the elements of the template doc's Body.
    switch (templateBody.getChild(i).getType()) { //Deal with the various types of Elements we will encounter and append.
      case DocumentApp.ElementType.PARAGRAPH:
        thisBody.appendParagraph(templateBody.getChild(i).copy());
        break;
      case DocumentApp.ElementType.LIST_ITEM:
        thisBody.appendListItem(templateBody.getChild(i).copy());
        break;
      case DocumentApp.ElementType.TABLE:
        thisBody.appendTable(templateBody.getChild(i).copy());
        break;
    }
  }

  return thisDoc;
}

如果您有兴趣了解有关 Document 的 Body 对象的结构的更多信息,我在这里写了一个长答案。它主要涵盖选择,但信息都是适用的。


推荐阅读