本文介绍了Google文档脚本可插入另一个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to use custom menu to insert another entire document.

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

The idea is that I have created a set of google docs with custom tables in each and then from the menu the user can just run a script to insert the table/template.

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

Creating the menu is easy (.createMenu) and adding menu items I can do. But how then do I create a script that copies the entirety of another google document (based on doc.id) and inserts into my current document?

推荐答案

您可以通过获取正文,并将其子元素附加到当前文档中.

You can do this by getting the Body of one document and appending its child Elements to the current document.

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;
}

如果您有兴趣了解有关文档正文对象结构的更多信息,我在这里写下了长答案.它主要涵盖选集,但所有信息均适用.

If you are interested in learning more about the structure of a Document's Body object, I wrote up a long answer here. It covers Selections mainly, but the information is all applicable.

这篇关于Google文档脚本可插入另一个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 21:55