繁体   English   中英

使用 Apps 脚本将部分内容从 Google Docs 复制到另一个 Doc

[英]Copying a section from Google Docs to another Doc using Apps Script

我已经成功地使用此代码将一个文档的全部内容复制到另一个文档中:

const newestFile = DocumentApp.openById("ID").getBody();
const archive = DocumentApp.openById("ID").getBody();
let index = 12;
  let el, type;
  for (let i = 0; i < newestFile.getNumChildren(); i++){
    el = newestFile.getChild(i);
    type = el.getType();
    switch (type){
      case DocumentApp.ElementType.PARAGRAPH:
        archive.insertParagraph(index,el.copy());
        index++;
        break;
      case DocumentApp.ElementType.LIST_ITEM:
        archive.insertListItem(index,el.copy());
        index++;
        break;
      case DocumentApp.ElementType.TABLE:
        archive.insertTable(index,el.copy());
        index++;
        break;
    }
  }

但是,我现在需要将一个文档的一部分复制到另一个文档中,但我无法弄清楚。 如果我知道如何获取任何元素的 body 索引,我可以用同样的方法来做,但我不知道这是否可行。 我需要复制的文本将始终以特定文本(“当前周”)开头,并在特定文本(“ARCHIVE”)之前立即结束。

描述

这是一个如何在特定文本之间复制的简单示例。 我只介绍了段落和表格,但可以处理任何其他类型的元素。

测试文件

在此处输入图像描述

脚本

function myFunction() {
  try {
    let doc = DocumentApp.getActiveDocument();
    let body = doc.getBody();
    let count = body.getNumChildren();
    doc = DocumentApp.create("dummy");
    let copy = doc.getBody();
    let start = false;

    for( let i=0; i<count; i++ ) {
      let child = body.getChild(i);
      if( child.getType() == DocumentApp.ElementType.PARAGRAPH ) {
        if( child.asParagraph().findText("Current Week") ) start = true; 
        if( start ) copy.appendParagraph(child.asParagraph().copy());
        if( child.asParagraph().findText("ARCHIVE") ) break;
      }
      else if( child.getType() == DocumentApp.ElementType.TABLE ) {
        if( start ) copy.appendTable(child.asTable().copy());
      }
    }
  }
  catch(err) {
    console.log("Error in myFunction - "+err)
  }
}

参考

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM