Need alternative to .makeCopy in Google Apps Script to decrease run time - performance

I wrote a mail merge script that works great, but execution transcripts revealed that the .makeCopy task alone consumed 60% of the 6 minute run time. I am trying to re-write the script in a way that enables me to:
Open a document template
populate the body of the template with spreadsheet data
create a new document
copy the body of the populated template to the new document
save the new document as a PDF, attach it to an email and send it
delete the new document (I don't need to retain a copy)
At present, I am receiving a "TypeError" appendtoDoc is not a function, it is undefined." Error in line 72.
//Creates the custom menu in the spreadsheet "Run Script"
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Script')
.addItem('Create Certs', 'menuItem1')
.addToUi();
}
//Nest the createDocument function within the menuItem1 function for execution
function menuItem1() {
function createDocFromSheet() {
}
//Defines the start row and calculates the number of rows to be processed
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = Browser.inputBox("Enter Start Row");
var endRow = Browser.inputBox("Enter End Row");
var numRows = (endRow - startRow) + 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 7);
//defines the variables and the email body
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var date = row[0];
var nic = row[1];
var course = row[2];
var lastname = row[3];
var firstname = row[4];
var middle = row[5]
var email = row[6];
var docname = lastname+" "+nic+" PME Cert";
var subjectTxt = "NWC "+ course +" Online PME Course Certificate";
var fullBody = "PME COURSE COMPLETION CERTIFICATE" + "\n\n";
fullBody += "Your " + course + " course completion certificate is attached." + "\n\n";
fullBody += "Regards," + "\n\n";
fullBody += "Professor Steve Pierce" + "\n";
fullBody += "U.S. Naval War College "+ "\n";
fullBody += "Online PME Program Team" + "\n\n";
fullBody += "Learn more about NWC's Online PME Program at the link below:" + "\n";
fullBody += "http://www.usnwc.edu/Academics/College-of-Distance-Education/PME-(1).aspx" + "\n";
// The old makeCopy code
// var docId = DriveApp
// .getFileById("1CjdoldpJmPskkqStpmBk3dRznFyURgY5mMsfVHfIGz4")
// .makeCopy(docname).getId();
// Open the document template
//function createDocFromSheet(){
var templateid = "1CjdoldpJmPskkqStpmBk3dRznFyURgY5mMsfVHfIGz4"
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
//create the new document
var newDoc = DocumentApp.create(lastname+" "+nic+" PME Cert");
var newDocId = newDoc.getId()
var file = DriveApp.getFileById(newDocId)
// fill in the template with data
for (var i in data){
var row = data[i];
// opens the template and populates it with data from the sheet
var docid = DriveApp.getFileById(templateid).getId();
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
body.replaceText('fname', firstname);
body.replaceText('lname', lastname);
body.replaceText('midname', middle);
body.replaceText('course', course);
body.replaceText('date', date);
doc.saveAndClose();
// appends data from the template to the new document
var body = doc.getActiveSection();
var newBody = newDoc.getActiveSection();
appendToDoc(body, newBody);
DocsList.getFileById(docid).setTrashed(true); //deletes the temp file
}
}
function appendToDoc(src, dst) {
for (var i = 0; i < src.getNumChildren(); i++) {
appendElementToDoc (dst, src.getChild(i));
}
}
function appendElementToDoc (doc, object) {
var type = object.getType();
var element = object.copy();
if (type == DocumentApp.ElementType.PARAGRAPH) {
if (element.asParagraph().getNumChildren() != 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) {
var blob = element.asParagraph().getChild(0).asInlineImage().getBlob();
doc.appendImage(blob);
}
else doc.appendParagraph(element.asParagraph());
}
MailApp.sendEmail(email, subjectTxt, fullBody, {attachments: Newdoc.getAs("application/pdf")});
SpreadsheetApp.flush ();
DriveApp.getFileById(docId).setTrashed(true);
}}}

I modified your script to do it differently: I took a template, did replaceText then created a pdf from the changed template and sent the email; then I did replaceText again, pdf, email etc etc. I could email 10 certs in 15 secs this way. I didn't try a bigger number, and didn't check for errors.
function creatCertPdfAndEmail() {
var sheet = SpreadsheetApp.openById('1fDe0ju0zkDr0cdA5hWBC4RsxZgFv6mIFn6W1WU-0S0w').getSheets()[0]; //I created a separate spreadsheet for testing purposes.
var startRow =2;
var endRow =10 ;
var numRows = (endRow - startRow) + 1;
var dataRange = sheet.getRange(startRow, 1, numRows, 7);
var counter =0;
var data = dataRange.getValues();
var templateid = "1DizlNa2ENpEMTUGhM78J0ozgh8A8Sc9fI1q1XmhvuLk"
var docid = DriveApp.getFileById(templateid).getId();
var dateOld;
var courseOld;
var allTheNameOld;
for (var i = 0; i < data.length; ++i) {
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
var row = data[i];
var date = new Date().getTime() - new Date(row[0]).getTime(); //like this for testing to get a different value on each pdf
var nic = row[1];
var course = row[2];
var lastname = row[3];
var firstname = row[4];
var middle = row[5]
var email = row[6];
// var docname = lastname+" "+nic+" PME Cert"; //not used in this version
var subjectTxt = "NWC "+ course +" Online PME Course Certificate";
var fullBody = "PME COURSE COMPLETION CERTIFICATE" + "\n\n";
fullBody += "Your " + course + " course completion certificate is attached." + "\n\n";
fullBody += "Regards," + "\n\n";
fullBody += "Professor Steve Pierce" + "\n";
fullBody += "U.S. Naval War College "+ "\n";
fullBody += "Online PME Program Team" + "\n\n";
fullBody += "Learn more about NWC's Online PME Program at the link below:" + "\n";
fullBody += "http://www.usnwc.edu/Academics/College-of-Distance-Education/PME-(1).aspx"
+ "\n";
var row = data[i];
var allTheName = firstname+' '+middle+' '+lastname
if(counter ==0){
body.replaceText('allTheName',allTheName); // body.replaceText('Congratulations .*?\.',allTheName);
body.replaceText('coursex', course);
body.replaceText('datex', date);
}
else {
body.replaceText(allTheNameOld,allTheName);
body.replaceText(courseOld, course);
body.replaceText(dateOld, date);
}
dateOld = date;
courseOld = course;
allTheNameOld = allTheName
counter ++
doc.saveAndClose()
var attachment = doc.getAs("application/pdf")
MailApp.sendEmail(email, subjectTxt, fullBody, {attachments: attachment});
}
}

I tried to re-create your basic code structure in a simpler format, trying to reproduce the error.
//Nest the createDocument function within the menuItem1 function for execution
function menuItem1() {
function createDocFromSheet() {}
for (var i = 0; i < 2; ++i) {
//create the new document
Logger.log("First Loop ran i = " + i);
for (var i = 0; i < 2; ++i) {
Logger.log(' Inner For loop: i = ' + i)
appendToDoc();
}
}
function appendToDoc() {
Logger.log('appendToDoc ran!');
for (var i = 0; i < 2; ++i) {
Logger.log('appendToDoc For Loop i=' + i);
appendElementToDoc();
}
}
function appendElementToDoc() {
Logger.log('appendElementToDoc ran!');
Logger.log('');
}
}
That code actually runs for me, and is able to access the appendToDoc function when I run the menuItem1() function.
It looks like you have a function function createDocFromSheet() {} with nothing in it. I don't understand that.

Related

Google Apps Script run faster

Below I have some code I have running for a spreadsheet. Right now it takes a min or two to run through the script. I was wondering if anyone has any suggestions on how to re-work my code to run a little faster.
What the code does is search on a tab in the sheet called "set up" for check-marked items in a list that I would like included in my "Master Sheet". Then go to my sheet which contains all of the information that I would like copied and pasted over according to what is check marked on my set-up page. Then copy and paste those line items to the master sheet.
function allToMaster(){
var sss = SpreadsheetApp.getActive();
var ssAll = sss.getSheetByName("FF All");
var ssMaster = sss.getSheetByName("FF Master");
var ssSetup = sss.getSheetByName("FF Setup");
ssMaster.clear();
var masterCounter = 2;
ssAll.getRange("P:P").clear();
var sourceRange = ssAll.getRange(1,1,1,15);
sourceRange.copyTo(ssMaster.getRange(1,1));
//get last row of FF All
var lastRowAll = ssAll.getLastRow();
var lastRowMaster = ssMaster.getLastRow();
ssAll.getRange("P2:P" + lastRowAll).setFormula("=index('FF Setup'!B:B,match(B2,'FF Setup'!C:C,0))");
ssMaster.setRowHeightsForced(2, 500, 26);
for (i=2;i<=lastRowAll;i++){
if (ssAll.getRange(i,1).getBackground() == "#a8d08d"){
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter++;
} else if (ssAll.getRange(i,1).getBackground() == "#e2efd9"){
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter++;
} else {
if (ssAll.getRange("P" + i).getValue() == true) {
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
ssMaster.setRowHeightsForced(masterCounter, 1, 136);
masterCounter++;
}
}
}
ssAll.getRange("P:P").clear();
//Clear Empty Subtitles
var lastRowMaster = ssMaster.getLastRow();
for (i=2;i<=lastRowMaster;i++){
if (ssMaster.getRange(i,1).getBackground() == "#e2efd9"){
if(ssMaster.getRange((i+1),1).getBackground() == "#e2efd9" || ssMaster.getRange((i+1),1).getBackground() == "#a8d08d"){
ssMaster.deleteRow(i);
ssMaster.insertRowAfter(500);
i=i-1;
}
}
}
//Clear Empty Titles
var lastRowMaster = ssMaster.getLastRow();
for (i=2;i<=lastRowMaster;i++){
if (ssMaster.getRange(i,1).getBackground() == "#a8d08d"){
if(ssMaster.getRange((i+1),1).getBackground() == "#a8d08d"){
ssMaster.deleteRow(i);
ssMaster.insertRowAfter(500);
i=i-1;
}
}
}
//Find the row with "Delivery"
var deliveryRow = getRowOf("DELIVERY", "FF All", 1);
var sourceRange = ssAll.getRange(deliveryRow,1,(lastRowAll - deliveryRow + 1),15);
var masterCounter = ssMaster.getLastRow()
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter = masterCounter + lastRowAll - deliveryRow - 2;
//.setFormula('=SUMA(J264:J275)');
// ssMaster.getRange(masterCounter, 10).setFormula("=sum(J2:J" + (masterCounter - 1) + ")");
//ssMaster.getRange(masterCounter, 11).setFormula("=sum(K2:K" + (masterCounter - 1) + ")");
//ssMaster.getRange(masterCounter, 13).setFormula("=sum(M2:M" + (masterCounter - 1) + ")");
//ssMaster.getRange(masterCounter, 15).setFormula("=M" + masterCounter + " - K" + masterCounter);
}
function getRowOf(value, sheet, col){
var dataArr = SpreadsheetApp.getActive().getSheetByName(sheet).getRange(4, col, 3500, 1).getValues();
for(var j = 0; j < dataArr.length; j ++){
var currVal = dataArr[j][0];
if(currVal == value){
return j+4;
break;
}
}
return 0;
}
You need to change the loops as they are doing several calls to Class SpreadsheetApp on each iteration.
Regarding the first loop,
for (i=2;i<=lastRowAll;i++){
if (ssAll.getRange(i,1).getBackground() == "#a8d08d"){
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter++;
} else if (ssAll.getRange(i,1).getBackground() == "#e2efd9"){
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
masterCounter++;
} else {
if (ssAll.getRange("P" + i).getValue() == true) {
var sourceRange = ssAll.getRange(i,1,1,15);
sourceRange.copyTo(ssMaster.getRange(masterCounter,1));
ssMaster.setRowHeightsForced(masterCounter, 1, 136);
masterCounter++;
}
}
}
Instead of getting the background of one cell at a time (ssAll.getRange(i,1).getBackground()), before the loop get the backgrounds of all the cells before the loop, i.e.
const backgrounds = ssAll.getRange(2,1,lastRowAll).getBackgrounds();
then replace ssAll.getRange(i,1).getBackground() by backgrounds[i-1][0].
Do the something similar about ssAll.getRange("P" + i).getValue(), before the loop get the all values of the P column:
const values = ssAll.getRange("P" + i + ":P" + lastRowAll).getValues()
then replace ssAll.getRange("P" + i).getValue() by values[i-1][0]`.
It might be also possible to optimize further the first loop depending on if you really need to copy the ranges (besides values, include borders, background, notes, etc.) or if you only need the values.
Another option is to use the Advances Sheets Services but this implies to make a completely different implementation.

How to deal with exception error when creating event from sheet?

In my mind, the script below takes a form submission gathered on a sheet and books it into a calendar (calId). In reality, however, the script falls apart at var event = thisCalendar.createEvent(:
Exception: Invalid argument: booker.
function calendarUpload() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Form Responses 1");
var Avals = ss.getRange("A1:A").getValues();
var lastRow = Avals.filter(String).length;
Logger.log(lastRow);
for (var i = 2; i <= lastRow ; i++) {
var approvalStatus = sheet.getRange(i,1).getValue();
var name = sheet.getRange(i,8).getValue(); //Event name.
var description = sheet.getRange(i,9).getValue(); //Event description, agenda.
var date = sheet.getRange(i,5).getValue(); //Event date.
var formattedStart = Utilities.formatDate(new Date(date), 'Europe/London', 'MMMM dd, yyyy');
var startTime = sheet.getRange(i,6).getValue(); //Event starting time.
var formattedSTime = Utilities.formatDate(new Date(startTime), 'Europe/London','hh:mm');
var endTime = sheet.getRange(i,7).getValue(); //Estimated end time of event.
var formattedETime = Utilities.formatDate(new Date(endTime), 'Europe/London','hh:mm');
var guests = sheet.getRange(i,15,1,10).getValues(); //Event guests by email address.
var staffMember = sheet.getRange(i,10).getValue(); //Meeting with... Determines Calendar ID (CalID).
var calId = sheet.getRange(i,11).getValue(); //Calendar.
var booker = sheet.getRange (i,3).getValue(); //The person booking the meeting.
var bookerEmail = sheet.getRange(i,4).getValue(); //Email booker, adds to guest list.
var eventStatus = sheet.getRange(1,1,i,12).getCell(i,12);
//Create eventName based on reason for meeting.
if (name == "one-on-one"){
var title = "ℳ " + booker + " and " + staffMember;
} else {
var title = name
}
Logger.log(eventStatus);
Logger.log(title);
Logger.log(formattedStart);
Logger.log(formattedSTime);
Logger.log(formattedETime);
Logger.log(guests);
var startDateandTime = (formattedStart+" "+formattedSTime);
var endDateandTime = (formattedStart+" "+formattedETime);
Logger.log(startDateandTime);
if (approvalStatus == "Approved" && eventStatus.isBlank()){
var thisCalendar = CalendarApp.getCalendarById(calId);
Logger.log('calId: '+calId);
Logger.log(thisCalendar );
var event = thisCalendar.createEvent(
title,
new Date(startDateandTime),
new Date(endDateandTime),
{guests: guests && bookerEmail, description: description});
Logger.log('Event Series ID: ' + eventSeries.getId());
var setEventStatus = sheet.getRange(i,12).setValue('Event Series ID: ' + event.getId());
} else {
Logger.log("No Events Found");
}
}
}
The logs seem to show that things go smoothly. Is there anything that you'd do differently? What can I do about the Exception error?
Example sheet.

Is there a way to speed up this for loop in Google Script?

I have a for loop which is working on my google sheet but it takes around 5 minutes to filter through the 2100 rows of data. I have read about using filters and getting rid of the for loop all together but I'm fairly new to coding in Google Script and haven't been able to get my head around the syntax for this. Any advice greatly appreciated.
Code below:
function Inspect() {a
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var lastRow = srcSheet.getLastRow();
for (var i = 2; i <= lastRow; i++) {
var cell = srcSheet.getRange("A" + i);
var val = cell.getValue();
if (val == true) {
var srcRange = srcSheet.getRange("B" + i + ":I" + i);
var clrRange = srcSheet.getRange("A" + i);
var tarRow = tarSheet.getLastRow();
tarSheet.insertRowAfter(tarRow);
var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":H" + (tarRow+1));
var now = new Date();
var timeRange = tarSheet.getRange("I"+(tarRow+1));
timeRange.setValue(now);
srcRange.copyTo(tarRange);
clrRange.clear();
//tarRange.activate();
timeRange.offset(0, 1).activate();
}
}
};
Yes, to speed-up you will need to get all the values first and apply your logic to the obtained 2D-arrays instead of cells, at the end you will use setValues to update your sheet. I would go for something like this:
function Inspect() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var srcLastRow = srcSheet.getLastRow();
var tarLastRow = tarSheet.getLastRow();
var srcArray = srcSheet.getRange(1,1,srcLastRow,9).getValues();//(A1:I(lastrow))
var tarArray = tarSheet.getRange(1,1,tarLastRow,9).getValues();//(A1:I(lastrow))
for (var i = 1; i < srcArray.length; i++) {
var val = srcArray[i][0];
if (val == true) {
var copyValues = srcArray[i].slice(1);//Get all elements from the row excluding first column (srcSheet.getRange("B" + i + ":I" + i);)
var now = new Date();
copyValues[8]=now;//set the time on column 9 (array starts at position 0!)
var tarNewLine = copyValues;
tarArray.push(tarNewLine);
//clear values on source (except column A):
for(var j=1;j<srcArray[i].length;j++){
srcArray[i][j]="";
}
}
}
tarSheet.clear();
tarSheet.getRange(1, 1,tarArray.length,tarArray[0].length).setValues(tarArray);
srcSheet.clear();
srcSheet.getRange(1, 1,srcArray.length,srcArray[0].length).setValues(srcArray);
};
You cannot get around a loop, but you should reduce the number of calls to the SpreadsheetApp to a minimum, see Apps Script Best Practices
It is not the for loop, but those calls that make your code slow. Instead, work with arrays as much as you can. Loops become of a problem if they are nested - this is also something you should avoid.
Sample how to perform most calls to SpreadsheetApp outside of the loop and work with arrays:
function Inspect() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Inventory");
var tarSheet = sSheet.getSheetByName("Inspections");
var lastRow = srcSheet.getLastRow();
var Acolumn = srcSheet.getRange("A2:A" + lastRow);
var Avalues = Acolumn.getValues();
var srcRange = srcSheet.getRange("B2:I" + lastRow);
var srcValues = srcRange.getValues();
var array = [];
var now = new Date();
for (var i = 0; i < lastRow-1; i++) {
var val = Avalues[i][0];
if (val == true) {
srcValues[i].push(now);
array.push(srcValues[i]);
var clrRange = Acolumn.getCell(i+1, 1);
clrRange.clear();
}
}
var tarRow = tarSheet.getLastRow();
tarSheet.insertRowAfter(tarRow);
if(array.length!=0){
var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":I" + (tarRow + array.length));
tarRange.setValues(array);
}
};

I have a google script that creates QR codes and Barcode. the QR Codes show up twice. Once where its suppose to and then at the end of the document

The code below generates a label that has a QR Code and barcode. Currently I am trying to get both to work. They both show up in the label but when it does the QR code will be added in the correct spot but also will add extra qr codes on the last label generated. The two qr codes at the end are itemnum qr codes and they are not suppose to be there. It normally puts them ontop of each other i moved them so people could see. The barcodes generate just fine but they don't scan
TEST SCRIPT here is a link to test it.. This is a test script and not part of a business so its easy to do. Basically what needs done is click on My Custom Menu and select reset labels. Once the labels are created you can go to the labels tab and select a few labels with serial numbers then go back to the menu and select create labels for selected items.
//####################################### Create Zebra Label #########################
function createZebraLabel(monthlySheet, newSheetName) {
var parentFolder = DriveApp.getFolderById('1mUPLw1PSi-guH19uJPCPWmogkpdckLcW');
var createdoc = DocumentApp.create('Zebra Label').getId();
doc = DocumentApp.openById(createdoc);
var id = createdoc;
var docFile = DriveApp.getFileById(doc.getId());
var target = parentFolder;
var file1 = DriveApp.getFileById(id);
var mkfile1 = file1.makeCopy(newSheetName, target).getId();
doc = DocumentApp.openById(mkfile1);
docFile.setTrashed(true);
//325
var body = doc.getBody().setPageWidth(325).setPageHeight(180).setMarginTop(.2).setMarginBottom(.2);
// var body = doc.getBody().setPageWidth(144).setPageHeight(144).setMarginTop(.2).setMarginBottom(.2);
var sourceSpreadSheet = SpreadsheetApp.openById(monthlySheet);
var ss = sourceSpreadSheet.getSheetByName('Sheet1');
var startRow = 1; // First row of data to process
var numRows = 250; // Number of rows to process
var startColumn = 1; // A=1 B=2
var numColumns = 5; // Number of columns to process
var dataRange = ss.getRange(startRow, startColumn, numRows, numColumns);
var data = dataRange.getValues();
for (var i = 1; i < data.length; ++i) {
var row = data[i];
var actualrow = i;
var itemnum = row[0]; // A column
var desc = row[1]; // B column
var serial = row[2]; // D column
var bin = row[3]; // D column
var qty = row[4];
var styleLeft = {};
styleLeft[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
styleLeft[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleLeft[DocumentApp.Attribute.FONT_SIZE] = 14;
styleLeft[DocumentApp.Attribute.BOLD] = true;
var styleRight = {};
styleRight[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
styleRight[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleRight[DocumentApp.Attribute.FONT_SIZE] = 14;
styleRight[DocumentApp.Attribute.BOLD] = true;
var itemBarcode = {};
itemBarcode[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
itemBarcode[DocumentApp.Attribute.FONT_FAMILY] = 'Libre Barcode 39 Extended Text';
itemBarcode[DocumentApp.Attribute.FONT_SIZE] = 25;
itemBarcode[DocumentApp.Attribute.BOLD] = false;
var serialBarcode = {};
serialBarcode[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
serialBarcode[DocumentApp.Attribute.FONT_FAMILY] = 'Libre Barcode 39 Extended Text';
serialBarcode[DocumentApp.Attribute.FONT_SIZE] = 20;
serialBarcode[DocumentApp.Attribute.BOLD] = false;
var nospace = {};
nospace[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
nospace[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
nospace[DocumentApp.Attribute.FONT_SIZE] = 1;
nospace[DocumentApp.Attribute.BOLD] = true;
var text = body.editAsText();
var itemqrcode = UrlFetchApp.fetch('https://chart.googleapis.com/chart?chs=70x70&cht=qr&chl=' + itemnum);
var serialqrcode = UrlFetchApp.fetch('https://chart.googleapis.com/chart?chs=70x70&cht=qr&chl=' + serial);
if (itemnum != '') {
//#################### SERIAL ###################
if (serial != '') { // SERIAL NUMBER
body.appendParagraph('').setAttributes(nospace);
var paragraph = body.appendParagraph('Item Number: ' + itemnum).setAttributes(styleLeft);
paragraph.addPositionedImage(itemqrcode.getBlob()).setLayout(DocumentApp.PositionedLayout.WRAP_TEXT)
body.appendParagraph('*' + itemnum + '*').setAttributes(itemBarcode);
body.appendParagraph('\n\n').setAttributes(nospace).appendHorizontalRule();
//description
body.appendParagraph(desc).setAttributes(styleLeft);
body.appendParagraph('').setAttributes(nospace);
//serials
body.appendParagraph('').setAttributes(nospace).appendHorizontalRule();
var paragraph = body.appendParagraph('Serial Number: ' + serial).setAttributes(styleRight);
body.appendParagraph('*' + serial + '*').setAttributes(serialBarcode);
paragraph.addPositionedImage(serialqrcode.getBlob()).setLayout(DocumentApp.PositionedLayout.WRAP_TEXT)
body.appendParagraph('').setAttributes(nospace);
} else if (serial == '') { // NO SERIAL NUMBER
var styleCenter = {};
styleCenter[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
styleCenter[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleCenter[DocumentApp.Attribute.FONT_SIZE] = 18;
styleCenter[DocumentApp.Attribute.BOLD] = true;
var itemBarcode = {};
itemBarcode[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
itemBarcode[DocumentApp.Attribute.FONT_FAMILY] = 'Libre Barcode 39 Extended Text';
itemBarcode[DocumentApp.Attribute.FONT_SIZE] = 35;
itemBarcode[DocumentApp.Attribute.BOLD] = false;
var styleLocation = {};
styleLocation[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
styleLocation[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleLocation[DocumentApp.Attribute.FONT_SIZE] = 12;
styleLocation[DocumentApp.Attribute.BOLD] = true;
body.appendParagraph('').setAttributes(nospace);
var paragraph = body.appendParagraph('Item Number: ' + itemnum).setAttributes(styleLeft);
body.appendParagraph('*' + itemnum + '*').setAttributes(itemBarcode);
body.appendParagraph('\n').setAttributes(nospace).appendHorizontalRule();
//description
body.appendParagraph(desc).setAttributes(styleLeft);
body.appendParagraph('').setAttributes(nospace).appendHorizontalRule();
body.appendParagraph('Location: ' + bin + ' Qty: ' + qty).setAttributes(styleLocation);
body.appendParagraph('\n').setAttributes(nospace);
}
body.appendPageBreak();
}
}
var googledoc = doc.getUrl();
FinishedGoogleDoc(googledoc);
}
Below is my solution that does work.
/
/####################################### Create Zebra Label #########################
function createZebraLabel(monthlySheet,newSheetName){
var parentFolder=DriveApp.getFolderById('1mUPLw1PSi-guH19uJPCPWmogkpdckLcW');
var createdoc = DocumentApp.create('Zebra Label').getId();
doc = DocumentApp.openById(createdoc);
var id = createdoc;
var docFile = DriveApp.getFileById(doc.getId());
var target = parentFolder;
var file1 = DriveApp.getFileById(id);
var mkfile1 = file1.makeCopy(newSheetName, target).getId();
doc = DocumentApp.openById(mkfile1);
docFile.setTrashed(true);
//325
var body = doc.getBody().setPageWidth(325).setPageHeight(180).setMarginTop(.02).setMarginBottom(.02);
// var body = doc.getBody().setPageWidth(144).setPageHeight(200).setMarginTop(.01).setMarginBottom(.01);
var sourceSpreadSheet = SpreadsheetApp.openById(monthlySheet);
var ss = sourceSpreadSheet.getSheetByName('Sheet1');
var startRow = 1; // First row of data to process
var numRows = 250; // Number of rows to process
var startColumn = 1; // A=1 B=2
var numColumns = 5; // Number of columns to process
var dataRange = ss.getRange(startRow, startColumn, numRows, numColumns);
var data = dataRange.getValues();
for (var i = 1; i < data.length; ++i) {
var row = data[i];
var actualrow=i;
var itemnum = row[0]; // A column
var desc = row[1]; // B column
var serial = row[2]; // D column
var bin = row[3]; // D column
var qty =row[4];
if (itemnum != ''){
var styleITEMNUM = {};
styleITEMNUM[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
styleITEMNUM[DocumentApp.Attribute.VERTICAL_ALIGNMENT] =DocumentApp.VerticalAlignment.CENTER;
styleITEMNUM[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleITEMNUM[DocumentApp.Attribute.FONT_SIZE] = 14;
styleITEMNUM[DocumentApp.Attribute.BOLD] = true;
var styleDESC = {};
styleDESC[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
styleDESC[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleDESC[DocumentApp.Attribute.FONT_SIZE] = 10;
styleDESC[DocumentApp.Attribute.BOLD] = true;
var styleSERIAL = {};
styleSERIAL[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
styleSERIAL[DocumentApp.Attribute.VERTICAL_ALIGNMENT] =DocumentApp.VerticalAlignment.CENTER;
styleSERIAL[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleSERIAL[DocumentApp.Attribute.FONT_SIZE] = 12;
styleSERIAL[DocumentApp.Attribute.BOLD] = true;
var nospace = {};
nospace[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
nospace[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
nospace[DocumentApp.Attribute.FONT_SIZE] =-1;
nospace[DocumentApp.Attribute.BOLD] = true;
var text = body.editAsText();
var paraStyle = {};
paraStyle[DocumentApp.Attribute.PADDING_BOTTOM] = 0;
paraStyle[DocumentApp.Attribute.PADDING_TOP] = 0;
paraStyle[DocumentApp.Attribute.MARGIN_TOP] = 0;
paraStyle[DocumentApp.Attribute.SPACING_BEFORE] = 0;
paraStyle[DocumentApp.Attribute.SPACING_AFTER] = 0;
paraStyle[DocumentApp.Attribute.LINE_SPACING] = 0;
var itemqrcode = UrlFetchApp.fetch('https://chart.googleapis.com/chart?chs=80x80&cht=qr&chl='+itemnum);
var serialqrcode = UrlFetchApp.fetch('https://chart.googleapis.com/chart?chs=80x80&cht=qr&chl='+serial);
//#################### ITEM WITH SERIAL NUMBER ###################
if (itemnum != '' && serial != ''){ // SERIAL NUMBE
body.appendParagraph('').setAttributes(nospace);
var table = body.appendTable().setBorderWidth(0).setAttributes(paraStyle);
var tr = table.appendTableRow().setAttributes(paraStyle);
var td = tr.appendTableCell('').setWidth(80).setPaddingTop(0).setPaddingBottom(0).appendImage(itemqrcode.getBlob()).setAttributes(paraStyle);
var td = tr.appendTableCell('Item Number\n' +itemnum).setPaddingTop(0).setPaddingBottom(0).setAttributes(styleITEMNUM);
body.appendHorizontalRule().setAttributes(nospace);
body.appendParagraph(desc).setAttributes(styleDESC);
body.appendParagraph('').setAttributes(nospace).appendHorizontalRule().setAttributes(nospace);
body.appendParagraph('').setAttributes(nospace);
var table = body.appendTable().setBorderWidth(0).setAttributes(paraStyle);
var tr = table.appendTableRow().setAttributes(paraStyle);
var td = tr.appendTableCell('').setWidth(80).setPaddingTop(0).setPaddingBottom(0).appendImage(serialqrcode.getBlob()).setHeight(80);
var td = tr.appendTableCell('Serial Number\n ' +serial).setPaddingTop(0).setPaddingBottom(0).setAttributes(styleSERIAL);
}
else if (itemnum != '' && serial == ''){ // NO SERIAL NUMBER
var styleLocation = {};
styleLocation[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
styleLocation[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
styleLocation[DocumentApp.Attribute.FONT_SIZE] =12;
styleLocation[DocumentApp.Attribute.BOLD] = true;
body.appendParagraph('').setAttributes(nospace);
var table = body.appendTable().setBorderWidth(0).setAttributes(paraStyle);
var tr = table.appendTableRow().setAttributes(paraStyle);
var td = tr.appendTableCell('').setWidth(80).setPaddingTop(0).setPaddingBottom(0).appendImage(itemqrcode.getBlob()).setAttributes(paraStyle);
var td=tr.appendTableCell('Item Number\n' +itemnum).setAttributes(styleITEMNUM);
body.appendParagraph('\n').setAttributes(nospace).appendHorizontalRule();
body.appendParagraph(desc).setAttributes(styleDESC);
body.appendParagraph('\n').setAttributes(nospace).appendHorizontalRule();
body.appendParagraph('').setAttributes(nospace);
var table = body.appendTable().setBorderWidth(0).setAttributes(paraStyle);
var tr = table.appendTableRow().setAttributes(paraStyle);
var td=tr.appendTableCell('Location:'+bin).setWidth(200).setPaddingTop(0).setPaddingBottom(0).setAttributes(styleLocation);
var td=tr.appendTableCell('Qty: ' +qty).setAttributes(styleLocation);
}
body.appendPageBreak();
}
}
var googledoc = doc.getUrl();
FinishedGoogleDoc(googledoc);
}

Enhancing Performance in Student Info App

I've built a simple Student Information platform using Google Sheets. It allows the user to query, update and create new student info on a user interface. Please refer to this sheet to see how it works.
The functions to Refresh/Update/Save are inside the Actions button on a menu bar. Everything seems to work well however when the number of records increases, say above 100 records, all the functions slow down and it gets extremely slow with 200+ records.
Appreciate if anyone could help to take a look at the scripts as I suspect they need to be optimized.
Many thanks in advance!
function UpdateDataIntoMaster() { //This script is used in the SAVE button in UPDATE sheet)
/*Get data from UPDATE Sheet*/
var ss = SpreadsheetApp.openById("11Djp9UmXbtWv7VitZFfo0X4Ctet3O8Amh4xADNKOZgY");
var sheet = ss.getSheetByName('UPDATE');
var range = sheet.getRange("D30:AE30"); //All data transposed into this line. MUST be updated if more fields are added into the Data sheet
var values = range.getValues();
var rangeForKey = sheet.getRange("D30") //Student Name is used as the
key identifier
var keyValue = rangeForKey.getValue();
/*Pass in keyValue(identifier = Student Name)
and all data in the function below in order
to update master data sheet*/
updDbase(keyValue,values);
function updDbase(keyValue,values) {
var ss = SpreadsheetApp.openById("11Djp9UmXbtWv7VitZFfo0X4Ctet3O8Amh4xADNKOZgY")
var sheet = ss.getSheetByName('Data');
var data = sheet.getDataRange().getValues();
var noOfRow = values.length
var noOfCol = values[0].length
for (var i=0; i < data.length; i++) { // going through all the rows in Data sheet
var keyData = ss.getSheetByName("Data").getRange(i+1,1).getValue(); //Get the Student Name from Data sheet
if (keyData == keyValue) {
// for (var j=0; j < data[i].length; j++) { // this is going through all the cell of a row
var row = Number(i)+1;
var sh = SpreadsheetApp.getUi();
var response = sh.alert("Update Information","Are you sure you want to update the student information?", sh.ButtonSet.YES_NO);
if (response == sh.Button.YES)
{
var sheets = ss.getSheetByName("Data").getRange(row,1,noOfRow,noOfCol).setValues(values);
}//If response == YES
}
}
}
}
function CreateNew() {
/*Get data from Inquiry Sheet*/
var ss = SpreadsheetApp.openById("11Djp9UmXbtWv7VitZFfo0X4Ctet3O8Amh4xADNKOZgY");
var sheetNew = ss.getSheetByName('Create New');
var range = sheetNew.getRange("D30:AZE30"); //All data transposed into
this line
var values = range.getValues();
var rangeForKey = sheetNew.getRange("E30") //Using Student ID as key identifier
var keyValue = rangeForKey.getValue();
var noOfRow = values.length
var noOfCol = values[0].length
var sheetData = ss.getSheetByName('Data');
var lastRow = sheetData.getLastRow();
var data = sheetData.getDataRange().getValues();
for (var i=0; i < data.length; i++) { // going through all the rows in Data sheet
var keyData = sheetData.getRange(i+1,2).getValue(); //Get the Student ID from Data sheet
if (keyData == keyValue) {
AlertBox();//If Student ID is found, to prompt Student ID already
exist
return;
} //If
} //For
/*Confirming with user whether to proceed to create new entry*/
var sh = SpreadsheetApp.getUi();
var response = sh.alert("Create New Record","Are you sure you want to
create new student information?", sh.ButtonSet.YES_NO);
if (response == sh.Button.YES){
if (keyValue == ""){
var response = sh.alert("Create New Record","Unable to proceed
because Student ID is empty", sh.ButtonSet.OK);
return;}
else {
//var response = sh.alert("Create New Record","Unable to
proceed because Student ID is empty", sh.ButtonSet.OK);
var sheets =
sheetData.getRange(lastRow+1,1,1,noOfCol).setValues(values)
}
}//If
}
function EditStudentInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inquiry");
//var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
var protection = protections[i];
if (protection.canEdit()) {
protection.remove();
}
}
}
function EditContent() {
var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Update");
var rangeContentCol1 = s.getRange("E3:E23");
var CopyContentCol1 = s.getRange("E3:E23").getValues();
var rangeContentCol2 = s.getRange("I3:I23");
var CopyContentCol2 = s.getRange("I3:I23").getValues();
rangeContentCol1.clearContent();
rangeContentCol2.clearContent();
var PasteContentCol1 =
s.getRange("E3:E23").setValues(CopyContentCol1);
var PasteContentCol2 = s.getRange("I3:I23").setValues(CopyContentCol2);
}
A common performance mistake people with Apps Script is doing the .getRange().getValues() within their for loops. Performance-wise these get and set calls are quite expensive.
Lucky the fix for this is quite easy - get all the data at once first, then loops through it. You actually do this already, sort of. In your script you get the whole data range, but then only use a part of the data and instead do another getValues call. I've updated the two areas in your script that had getRange() calls in a for loop --> var keyData = data[i][0];
function UpdateDataIntoMaster() { //This script is used in the SAVE button in UPDATE sheet)
/*Get data from UPDATE Sheet*/
var ss = SpreadsheetApp.openById("11Djp9UmXbtWv7VitZFfo0X4Ctet3O8Amh4xADNKOZgY");
var sheet = ss.getSheetByName('UPDATE');
var range = sheet.getRange("D30:AE30"); //All data transposed into this line. MUST be updated if more fields are added into the Data sheet
var values = range.getValues();
var rangeForKey = sheet.getRange("D30") //Student Name is used as the
key identifier
var keyValue = rangeForKey.getValue();
/*Pass in keyValue(identifier = Student Name)
and all data in the function below in order
to update master data sheet*/
updDbase(keyValue,values);
function updDbase(keyValue,values) {
var ss = SpreadsheetApp.openById("11Djp9UmXbtWv7VitZFfo0X4Ctet3O8Amh4xADNKOZgY")
var sheet = ss.getSheetByName('Data');
var data = sheet.getDataRange().getValues();
var noOfRow = values.length
var noOfCol = values[0].length
for (var i=0; i < data.length; i++) { // going through all the rows in Data sheet
var keyData = data[i][0]; //Use the data that is already loaded.
if (keyData == keyValue) {
// for (var j=0; j < data[i].length; j++) { // this is going through all the cell of a row
var row = Number(i)+1;
var sh = SpreadsheetApp.getUi();
var response = sh.alert("Update Information","Are you sure you want to update the student information?", sh.ButtonSet.YES_NO);
if (response == sh.Button.YES)
{
var sheets = ss.getSheetByName("Data").getRange(row,1,noOfRow,noOfCol).setValues(values);
}//If response == YES
}
}
}
}
function CreateNew() {
/*Get data from Inquiry Sheet*/
var ss = SpreadsheetApp.openById("11Djp9UmXbtWv7VitZFfo0X4Ctet3O8Amh4xADNKOZgY");
var sheetNew = ss.getSheetByName('Create New');
var range = sheetNew.getRange("D30:AZE30"); //All data transposed into
this line
var values = range.getValues();
var rangeForKey = sheetNew.getRange("E30") //Using Student ID as key identifier
var keyValue = rangeForKey.getValue();
var noOfRow = values.length
var noOfCol = values[0].length
var sheetData = ss.getSheetByName('Data');
var lastRow = sheetData.getLastRow();
var data = sheetData.getDataRange().getValues();
for (var i=0; i < data.length; i++) { // going through all the rows in Data sheet
var keyData = data[i][0]; //Use the data that is already loaded.
if (keyData == keyValue) {
AlertBox();//If Student ID is found, to prompt Student ID already
exist
return;
} //If
} //For
/*Confirming with user whether to proceed to create new entry*/
var sh = SpreadsheetApp.getUi();
var response = sh.alert("Create New Record","Are you sure you want to
create new student information?", sh.ButtonSet.YES_NO);
if (response == sh.Button.YES){
if (keyValue == ""){
var response = sh.alert("Create New Record","Unable to proceed
because Student ID is empty", sh.ButtonSet.OK);
return;}
else {
//var response = sh.alert("Create New Record","Unable to
proceed because Student ID is empty", sh.ButtonSet.OK);
var sheets =
sheetData.getRange(lastRow+1,1,1,noOfCol).setValues(values)
}
}//If
}
function EditStudentInfo() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inquiry");
//var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
var protection = protections[i];
if (protection.canEdit()) {
protection.remove();
}
}
}
function EditContent() {
var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Update");
var rangeContentCol1 = s.getRange("E3:E23");
var CopyContentCol1 = s.getRange("E3:E23").getValues();
var rangeContentCol2 = s.getRange("I3:I23");
var CopyContentCol2 = s.getRange("I3:I23").getValues();
rangeContentCol1.clearContent();
rangeContentCol2.clearContent();
var PasteContentCol1 =
s.getRange("E3:E23").setValues(CopyContentCol1);
var PasteContentCol2 = s.getRange("I3:I23").setValues(CopyContentCol2);
}
Give this a test and let me know if it helps!

Resources