Created
December 24, 2022 20:13
-
-
Save phillypb/d415f4ae18e2f1e337c401c543230786 to your computer and use it in GitHub Desktop.
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
/* | |
Create menu item to run script from spreadsheet. | |
*/ | |
function onOpen() { | |
SpreadsheetApp.getUi() | |
.createMenu('Create Doc') | |
.addItem('Create Doc', 'getSpreadsheetData') | |
.addToUi(); | |
} | |
function logEvent(action) { | |
// get the user running the script | |
var theUser = Session.getActiveUser().getEmail(); | |
// get the relevant spreadsheet to output log details | |
var ss = SpreadsheetApp.getActiveSpreadsheet(); | |
var logSheet = ss.getSheetByName('Log'); | |
// create and format a timestamp | |
var dateTime = new Date(); | |
var timeZone = ss.getSpreadsheetTimeZone(); | |
var niceDateTime = Utilities.formatDate(dateTime, timeZone, "dd/MM/yy @ HH:mm:ss"); | |
// create array of data for pasting into log sheet | |
var logData = [niceDateTime, theUser, action]; | |
// append details into next row of log sheet | |
logSheet.appendRow(logData); | |
} | |
/* | |
Get data from the Google Sheet. | |
*/ | |
function getSpreadsheetData() { | |
// Log starting of the script | |
logEvent('Script has started'); | |
// get current spreadsheet | |
var spreadsheet = SpreadsheetApp; | |
var ss = spreadsheet.getActiveSpreadsheet(); | |
// display Toast notification to inform starting of the script | |
ss.toast('Script has now started', 'Start'); | |
// get Config sheet | |
var configSheet = ss.getSheetByName('Config'); | |
// get Drive Folder ID for storing created Docs | |
var destinationFolderId = configSheet.getRange(1, 2).getValue(); | |
Logger.log('destinationFolderId is: ' + destinationFolderId); | |
// get Template File ID | |
var templateFileId = configSheet.getRange(2, 2).getValue(); | |
Logger.log('templateFileId is: ' + templateFileId); | |
// get Data sheet | |
var dataSheet = ss.getSheetByName('Data'); | |
// get last column number (minus 1 for Google Doc hyperlink column) | |
var lastCol = dataSheet.getLastColumn() - 1; | |
// get current row number from active cell where user clicked | |
var activeCell = dataSheet.getActiveCell(); | |
var currentRowNo = activeCell.getRow(); | |
Logger.log('currentRowNo is: ' + currentRowNo); | |
// get row data | |
var data = dataSheet.getRange(currentRowNo, 1, 1, lastCol).getValues(); | |
Logger.log(data); | |
// create a name:value pair array to send the data to the next Function | |
var spreadsheetData = { | |
spreadsheet: spreadsheet, dataSheet: dataSheet, destinationFolderId: destinationFolderId, | |
templateFileId: templateFileId, currentRowNo: currentRowNo, data: data | |
}; | |
// run Function to create Google Doc for given row of data | |
createDoc(spreadsheetData); | |
} | |
/* | |
Create the Google Doc. | |
*/ | |
function createDoc(spreadsheetData) { | |
// Log starting createDoc Function | |
logEvent('Starting createDoc Function'); | |
// separate out data from name:value pair array | |
var spreadsheet = spreadsheetData['spreadsheet']; | |
var ss = spreadsheet.getActiveSpreadsheet(); | |
var dataSheet = spreadsheetData['dataSheet']; | |
var destinationFolderId = spreadsheetData['destinationFolderId']; | |
var templateFileId = spreadsheetData['templateFileId']; | |
var currentRowNo = spreadsheetData['currentRowNo']; | |
var data = spreadsheetData['data']; | |
try { | |
// try getting the Folder and then set variable as true if successful | |
var destinationFolder = DriveApp.getFolderById(destinationFolderId); | |
var gotDestinationFolder = true; | |
} | |
catch (e) { | |
// if failed set variable as false and Log | |
var gotDestinationFolder = false; | |
logEvent('Failed to get destinationFolder with error: ' + e.stack); | |
} | |
// only proceed if got destination Drive Folder | |
if (gotDestinationFolder) { | |
try { | |
// try getting the Template File and then set variable as true if successful | |
var templateFile = DriveApp.getFileById(templateFileId); | |
var gotTemplateFile = true; | |
} | |
catch (e) { | |
var gotTemplateFile = false; | |
logEvent('Failed to get templateFile with error: ' + e.stack); | |
} | |
} else { | |
// do nothing | |
}; | |
// only proceed if got Template File also | |
if (gotTemplateFile) { | |
// extract values from array of data | |
var emailAddress = data[0][0]; | |
var firstName = data[0][1]; | |
var lastName = data[0][2]; | |
var shoeSize = data[0][3]; | |
// create name for new File | |
var newFileName = 'New Doc - ' + lastName + ' - ' + firstName; | |
// make copy of Template File and place in destination Drive Folder | |
var newFile = templateFile.makeCopy(newFileName, destinationFolder); | |
// get ID and Url of new File | |
var newFileID = newFile.getId(); | |
var newFileUrl = newFile.getUrl(); | |
try { | |
// try opening the new File, get its Body and then set variable as true if successful | |
var newFileBody = DocumentApp.openById(newFileID).getBody(); | |
var openNewFile = true; | |
} | |
catch (e) { | |
// if failed set variable as false and Log | |
var openNewFile = false; | |
logEvent('Failed to open newFileBody with error: ' + e.stack); | |
} | |
// only proceed if got Body of new File | |
if (openNewFile) { | |
// replace tags with data from sheet | |
newFileBody.replaceText('<<emailAddress>>', emailAddress); | |
newFileBody.replaceText('<<firstName>>', firstName); | |
newFileBody.replaceText('<<lastName>>', lastName); | |
newFileBody.replaceText('<<shoeSize>>', shoeSize); | |
// paste a hyperlink to new File in spreadsheet | |
var newFileLink = '=HYPERLINK("' + newFileUrl + '","' + newFileName + '")'; | |
dataSheet.getRange(currentRowNo, 5).setFormula(newFileLink); | |
// refresh spreadsheet to links appear as soon as added | |
spreadsheet.flush(); | |
} else { | |
// do nothing | |
}; | |
} else { | |
// do nothing | |
}; | |
// display Toast notification to inform end of the script | |
ss.toast('Script has now ended', 'End'); | |
// Log end of the script | |
logEvent('Script has ended'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment