【问题标题】:Google Docs script to insert another document谷歌文档脚本插入另一个文档
【发布时间】:2019-02-21 23:24:58
【问题描述】:

我希望使用自定义菜单来插入另一个完整的文档。

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

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

【问题讨论】:

    标签: google-apps-script google-docs


    【解决方案1】:

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

    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 对象的结构,我写了一个 long answer here。它主要涵盖了选择,但信息都是适用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-15
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-12
      • 2020-11-27
      • 1970-01-01
      相关资源
      最近更新 更多