Skip to content

Instantly share code, notes, and snippets.

@misterhay
Created January 7, 2017 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misterhay/545afd65499f253450dbfe5210173a33 to your computer and use it in GitHub Desktop.
Save misterhay/545afd65499f253450dbfe5210173a33 to your computer and use it in GitHub Desktop.
Starting from a Google Spreadsheet containing links to student response documents, this creates a single document containing all of their responses.
function addMenu() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Student Responses').addItem('Concatenate all responses', 'concatenateResponses').addToUi();
}
function concatenateResponses() {
var responsesDoc = DocumentApp.create('Student Responses');
var responsesDocID = responsesDoc.getId();
var sheet = SpreadsheetApp.getActiveSheet();
var columnContainingLinksToDocuments = 6;
var lastRow = sheet.getLastRow();
var docIDs = [];
// loop through the cells to get the document IDs for all the response documents
for (var x=2; x<=lastRow; x++) {
var docLink = sheet.getRange(x, columnContainingLinksToDocuments).getValue();
var splitDocLink = docLink.split('/');
var docID = splitDocLink[7];
docIDs[x-2] = docID;
}
mergeGoogleDocs(docIDs, responsesDocID);
}
// Retrieved and modified from from https://ctrlq.org/code/19892-merge-multiple-google-documents
function mergeGoogleDocs(docIDs, responsesDocID) {
var baseDoc = DocumentApp.openById(responsesDocID);
var body = baseDoc.getActiveSection();
for (var i=0; i<docIDs.length; i++) {
var studentNumber = i+1
body.appendParagraph('Student Number ' + studentNumber).setBold(true).setItalic(true);
var otherBody = DocumentApp.openById(docIDs[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
throw new Error("Unknown element type: "+type);
}
body.appendHorizontalRule();
body.appendPageBreak();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment