Created
July 20, 2020 18:24
-
-
Save northwestcoder/838e9787baacb500d45ea84175df7dea to your computer and use it in GitHub Desktop.
Google App Script merge documents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
This script generates a google doc from multiple 'child' docs. | |
It is meant to be triggered from an AppSheet.com app vis a vis a Google Sheet, e.g.: | |
AppSheet adds record/event to Google Sheet >> Trigger listening to Google Sheet >> This script invoked | |
*/ | |
// the Google Sheet that is to be queried | |
gsheetID = "A SHEET ID THAT IS MANAGED BY APPSHEET DOT COM"; | |
// the tab inside this sheet, if you copied a sample it should be 'Documents' | |
gsheetTabName = "Documents"; | |
function onChange(e) { | |
finalDoc = DocumentApp.create('MERGE-TEST'); | |
var body = finalDoc.getActiveSection(); | |
var mergeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; | |
var range = mergeSpreadsheet.getRange('B2:B500'); | |
range.activate(); | |
var rows = range.getValues(); | |
var docrows = [] | |
for (var i = 0; i < rows.length ; i++){ | |
if(rows[i][0].length > 0) | |
{ | |
docrows.push(rows[i][0]); | |
} | |
} | |
// we only want rows which are not null, e.g. they have a google doc id in them | |
// Logger.log(docrows) | |
for (var i = 0; i < docrows.length; ++i ) { | |
var otherBody = DocumentApp.openById(docrows[i]).getActiveSection(); | |
var totalElements = otherBody.getNumChildren(); | |
for( var j = 0; j < totalElements; ++j ) { | |
var element = otherBody.getChild(j).copy(); | |
var type = element.getType(); | |
if( type == DocumentApp.ElementType.PARAGRAPH ) | |
body.appendParagraph(element); | |
else if( type == DocumentApp.ElementType.TABLE ) | |
body.appendTable(element); | |
else if( type == DocumentApp.ElementType.LIST_ITEM ) | |
body.appendListItem(element); | |
else if( type == DocumentApp.ElementType.HORIZONTAL_RULE ) | |
body.appendHorizontalRule() | |
else if( type == DocumentApp.ElementType.PAGE_BREAK) | |
body.appendPageBreak() | |
else if( type == DocumentApp.ElementType.INLINE_IMAGE) | |
body.appendImage(element) | |
else if( type == DocumentApp.ElementType.TEXT) | |
body.appendParagraph(element) | |
else | |
Logger.log("unknown doc part type"); | |
// or, optionally | |
// throw new Error("Unknown element type: "+type); | |
} | |
// after each iter let's add a page break | |
body.appendPageBreak() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment