Merge multiple docs into one in Google Docs
Originally written for bulldo.gs — republished here with the canonical link pointing home. I want to programmatically combine several Google Docs into one file without losing tables or list formatting. // Merges all source docs into destDocId, in order. // Run from the Apps Script editor; no triggers needed. function mergeDocs () { var sourceIds = [ ' DOC_ID_ONE ' , ' DOC_ID_TWO ' , ' DOC_ID_THREE ' ]; var dest = DocumentApp . openById ( ' DEST_DOC_ID ' ). getBody (); for ( var i = 0 ; i < sourceIds . length ; i ++ ) { var srcBody = DocumentApp . openById ( sourceIds [ i ]). getBody (); var total = srcBody . getNumChildren (); for ( var j = 0 ; j < total ; j ++ ) { var el = srcBody . getChild ( j ); var type = el . getType (); if ( type === DocumentApp . ElementType . PARAGRAPH ) { dest . appendParagraph ( el . asParagraph (). copy ()); } else if ( type === DocumentApp . ElementType . TABLE ) { dest . appendTable ( el . asTable (). copy ()); } else if ( type === DocumentApp . ElementType . LIST_ITEM ) { dest . appendListItem ( el . asListItem (). copy ()); } } } } Why there is no single appendElement call The Document service in Apps Script does not expose a generic appendElement method on Body . Every element type has its own typed append method: appendParagraph , appendTable , appendListItem , and so on. That means a merge loop that ignores element types will throw TypeError: el.copy is not a function the moment it hits a table, because you would be passing an Element where the API expects a Table . The fix is to call getType() on each child element and switch on DocumentApp.ElementType . The type enum values are strings like PARAGRAPH , TABLE , LIST_ITEM , INLINE_IMAGE , and HORIZONTAL_RULE . In practice the first three account for almost all real document content. The code above handles those three and silently skips anything else (images, rules) rather than crashing the entire merge. Getting the doc IDs and running the script The ID for any Google Doc is the lo