Google文档脚本可插入另一个文档

时间:2019-02-21 23:24:58

标签: google-apps-script google-docs

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

这个想法是,我创建了一组带有自定义表的google文档,然后用户可以从菜单中运行脚本以插入表/模板。

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

1 个答案:

答案 0 :(得分:0)

您可以通过获取一个文档的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。它主要涵盖选集,但所有信息均适用。

相关问题