google-apps-scriptgoogle-docs

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


I've successfully used this code to copy the entirety of one doc into another doc:

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

However, I now need to copy a portion of a doc into another doc, and I can't figure it out. If I knew how to get the body index of any element I could do it the same way, but I don't know if that's even possible. The text I need to copy out will always be preceded by a specific text ("Current Week") and end immediatly before a specific text ("ARCHIVE").


Solution

  • Description

    Here is a simple example of how to copy between certain text. I've only covered paragraphs and tables but any other type of Element can be handled.

    Test Document

    enter image description here

    Script

    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());
          }
          else if( child.getType() == DocumentApp.ElementType.LIST_ITEM ) {
            if( start ) {
              let listItem = child.asListItem();
              let glyphType = listItem.getGlyphType();
              listItem = copy.appendListItem(listItem.copy());
              listItem.setGlyphType(glyphType)
            }
          }
        }
      }
      catch(err) {
        console.log("Error in myFunction - "+err)
      }
    }
    

    Reference