Generate a Google Doc (and PDF) of row data when a cell in a row of a sheet is edited - pdf

I have a Google Form and Google Sheet set up to collect information I need. I currently have a script that will send me, and the form submitter, an email with a PDF attached that contains the contents of their form submission.
I am trying to edit that script and create another one that sends me a new version of the PDF after I go in and make a change to one of the cells associated with the original form submission (update the status of an issue, add notes, correct grammar, etc.).
This is what I have, I am still very new at programming and would appreciate any help...
(18 NOV #1425) It works! var last_column was not allowing the column after the edited cell to be defined. When I replaced last_column in var data with the actual number of columns that contained the data it worked great! Thank you to everyone who helped me figure this out, and learn a little along the way!
function onSheetEdit(e) {
var source = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = source.getSheetByName("Form Responses 1");
var range = source_sheet.getDataRange();
var ActiveRow = source_sheet.getActiveRange().getRow();
var data = source_sheet.getRange(ActiveRow,1,1,4).getValues();
var columnA = data[0][0];
var columnB = data[0][1];
var columnC = data[0][2];
var columnD = data[0][3];
(18 NOV #0800) Another friend suggested I change the beginning to this... The email also sends, and now I am getting "1" "1" "/" and "1" in my four document placeholders...
function onSheetEdit(e) {
var source_sheet = e.source.getActiveSheet();
if (source_sheet.getName() !== "Form Responses 1") return; //exit the script if edits are done on other sheets
var data = source_sheet.getRange(e.range.rowStart, 1, 1, source_sheet.getLastColumn())//(StartRow,StartColumn,NumberofRowstoGet,NumberofColumnstoGet)
.getValues()[0];
Logger.log(data);
var columnA = data[0][0];
var columnB = data[0][1];
var columnC = data[0][2];
var columnD = data[0][3];
(17 NOV #1845) I had a friend help me from work and this is as far as we got... The email sends now, but the placeholders are not populating the data correctly in the PDF file attachment. It appears that the only data that is populating is data from row 1, and of that data, only the cell that was edited, and the data in the cells to the right of it...
function onSheetEdit(e) {
var source = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = source.getSheetByName("Form Responses 1");
var range = source_sheet.getDataRange();
var last_column = source_sheet.getActiveRange().getColumn();
var ActiveRow = source_sheet.getActiveRange().getRow();
var data = source_sheet.getRange(ActiveRow,1,1,last_column).getValues();
var columnA = data[0][0];
var columnB = data[0][1];
var columnC = data[0][2];
var columnD = data[0][3];
(16 NOV #1700) I edited the script to this but still no emails generated. I get this error emailed to me when script fails: "Cell reference out of range (line 13, file "Copy of Form confirmation emails")". Line 13 is "var row".
function onSheetEdit() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = source.getActiveSheet()
var row = source_sheet.getActiveCell().getRow();
var last_column = source_sheet.getLastColumn();
var data = source_sheet.getRange(row,1,1,last_column).getValues();
var columnA = data[0][0];
var columnB = data[0][1];
var columnC = data[0][2];
var columnD = data[0][3];
(16 NOV # 1330) I tried this instead but still no emails generated...
function onSheetEdit() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var source_sheet = source.getActiveSheet()
var row = source_sheet.getActiveCell().getRow();
var last_column = source_sheet.getLastColumn();
var data = source_sheet.getRange(row,1,1,last_column);
var columnA = data.values[0];
var columnB = data.values[1];
var columnC = data.values[2];
var columnD = data.values[3];
Original script...
function onSheetEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var rows = sheet.getActiveCell().getRow();
var columnA = e.values[0];
var columnB = e.values[1];
var columnC = e.values[2];
var columnD = e.values[3];
var docTemplate = "1WyWeCLQQ3en1EbKjOLcWxlOLc0fHHDpZrB9yfXZ7nv8";
var docName = "Test form script";
var carbonCopyEmail = "jeffery.crane#goarmy.com";
var submitterEmail = columnB;
var dataName = columnC;
var submitDate = columnA;
var attachmentName = docName + ' for data ' + dataName
var submitterEmailPlaceholder = 'keyUsername';
var submitDatePlaceholder = 'keyTimestamp';
var templatePlaceholder1 = 'keyQuestion1';
var templatePlaceholder2 = 'keyQuestion2';
var submitterSubject = "Test Script Confirmation Email for data " + dataName;
var submitterBody = "Attached is a PDF confirmation sheet with the details of your submission of data: " + dataName + " submitted on " + submitDate;
var carbonCopySubject = "Test Script Submission Notification Email for data " + dataName;
var carbonCopyBody = "Attached is a PDF confirmation sheet with the details of " + submitterEmail + "'s submission of data: " + dataName + " on " + submitDate;
//Gets document template defined by the docID above, copys it as a new temp doc, and saves the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(attachmentName)
.getId();
//Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
//Get the document’s body section
var copyBody = copyDoc.getActiveSection();
//POSSIBLE MODIFICATION TO ADD LINES OF CODE
//Replace place holder keys with the spreadsheet values in the google doc template
//This section of the script looks for instances where the key appears in the Google Doc and replaces the instance
//with the defined variable
//For instance, whenever "keyUserName" (defined above as submitterEmailPlaceholder) appears in the Google Doc,
//the value from the spreadsheet in columnB replaces "keyUserName"
copyBody.replaceText(submitDatePlaceholder, columnA);
copyBody.replaceText(submitterEmailPlaceholder, columnB);
copyBody.replaceText(templatePlaceholder1, columnC);
copyBody.replaceText(templatePlaceholder2, columnD);
//Save and close the temporary document
copyDoc.saveAndClose();
//Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
//Attaches the PDF and sends the email to the form submitter
MailApp.sendEmail(submitterEmail, submitterSubject, submitterBody, {htmlBody: submitterBody, attachments: pdf});
//Attaches the PDF and sends the email to the recipients in copyEmail above
MailApp.sendEmail(carbonCopyEmail, carbonCopySubject, carbonCopyBody, {htmlBody: carbonCopyBody, attachments: pdf});
//Deletes the temporary file
DocsList.getFileById(copyId).setTrashed(true);
}

You cannot do data.values, data is a range object, you should do getValues() to get an array of values: data[row][col]
var data = source_sheet.getRange(row,1,1,last_column).getValues()
var columnA = data[0][0];
var columnB = data[1][0];
var columnC = data[2][0];
var columnD = data[3][0];

Why instead of mess manually with the cells values of the responses sheet you don't use the form edit link? You can put it into the mail you are already sending.
You can get it from:
var editLink = lastResponse.getEditResponseUrl();
When the form is submitted again from the edit link the script you wrote script will be run again sending the updated PDF.

Related

Locate rows with identical values in a column and email each of those rows in 1 email

I am trying to write an Apps script for my google sheet.
Problem: I have data with the following column headings: Email; ID; Category; $Amount; Comment. There are multiple rows that have the same ID. I need all rows with the same ID to be sent in an email to the email address associated with that line.
So the email for example could (doesn't have to be) a table with the data enclosed
[sample email][2]
Can anyone help me with this?
Here is some code I wrote in Apps Script trying to do this on my own but it doesn't work:
var Send = "Y";
function sendEmails() {
//specify the sheet and definitions
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var lastrow = sheet.getLastRow();
var startrow = 1; // This is the 1st row of data to process
var numrows = lastrow; //This is the number of rows to process
//This section formats the colums so they appear correctly in the html email below
var column = sheet.getRange("A:A");
column.setNumberFormat("#"); //simple plain text format
var column = sheet.getRange("B:B");
column.setNumberFormat("#"); //simple plain text format
var column = sheet.getRange("D:D");
column.setNumberFormat("#"); //simple plain text format
var column = sheet.getRange("E:E");
column.setNumberFormat("#"); //simple plain text format
var column = sheet.getRange("H:H");
column.setNumberFormat("$0.00"); //simple currency format
var column = sheet.getRange("I:I");
column.setNumberFormat("#"); //simple plain text format
var column = sheet.getRange("J:J");
column.setNumberFormat("#"); //simple plain text format
//This section specifies the actual data we will be working with
var datarange = sheet.getRange(startrow, 1, lastrow, 15) // Fetch the range of cells
var data = datarange.getValues(); // Fetch values for each row in the Range.
//Defining the Column data
for (var i = 0; i < data.length; ++i) {
var col = data[i];
var Name = col[0]; //Column starting at 0 from left to right
var EmailAddress = col[1]; //Column starting at 0 from left to right
var Send = col[2]; //Column starting at 0 from left to right
var LeaseID = col[3]; //Column starting at 0 from left to right
var ExpenseCategory = col[4]; //Column starting at 0 from left to right
var TransactionDate = col[5]; //Column starting at 0 from left to right
var Type = col[6]; //Column starting at 0 from left to right
var Amount = col[7]; //Column starting at 0 from left to right
var PayeeName = col[8]; //Column starting at 0 from left to right
var Comment = col[9]; //Column starting at 0 from left to right
var EmailSent = col[10]; //Column starting at 0 from left to right
var Subject = "xxxxxxx June Payment Detail"; //Suject for the email to be sent
var emailintro = //Introduction part of the email
'Hi' + Name + ',<br /><br />' +
'In order to ensure proper account credit, please see the details from this months payment below: <br /><br />'
var emailtrans = 'List' + ExpenseCategory + Amount + Comment + '<br /><br />'
var emailend = // The end of the email
'Please let us know if you have any questions. You may reach us at xxxxx#xxxxx.com'
var me = Session.getActiveUser().getEmail();
var aliases = GmailApp.getAliases(); //Gets the alias xxxxxx#xxxx.com from account
Logger.log(aliases); //logs the alias
//This section is the one that actually sends the emails
//if (EmailAddress != "" && EmailSent !=""{
if (aliases.length > 0) { // Prevents sending duplicates
GmailApp.sendEmail(EmailAddress, subject, emailintro + emailtrans + emailend, {
'from': aliases[0],
'replyto': 'xxxxxx#xxxxxx.com',
htmlbody: emailintro + emailtrans + emailend
});
sheet.getrange(startrow + i, 392).setVaue(SENT);
SpreadsheetApp.flush(); //Make Sure the cell is updated right away in case the script is interrupted
}
}
}
//}}else {}}}

Using getBlob() with activesheet to create pdf is missing recent updates [duplicate]

This question already has an answer here:
Creating and Sending sheets in the same function
(1 answer)
Closed 4 years ago.
I'm trying to save a single-sheet spreadsheet to pdf. Many blogs explain how to do this using getBlob() so I ended up with this:
var theBlob = jobSpreadSheet.getBlob().getAs('application/pdf');
var newFile = getPdfFolder().createFile(theBlob.setName(fileName + ".pdf"));
To create jobSpreadSheet I have created a new spreadsheet:
var tempSpreadsheet = SpreadsheetApp.create(name);
var driveTempFile = DriveApp.getFileById(tempSpreadsheet.getId());
var jobsFolder = getJobsFolder();
var driveNewFile = driveTempFile.makeCopy(name, jobsFolder);
var jobSpreadsheet = SpreadsheetApp.open(driveNewFile);
Next I copy a template into the new spreadsheet and remove the empty first sheet:
var jobCard = jobCardTemplate.copyTo(jobSpreadSheet).setName('Job Card');
jobSpreadSheet.deleteSheet(jobSpreadSheet.getSheets()[0]);
Then I update a few cells in the jobCard and finally create the pdf.
All the steps work except creating the pdf. The pdf is created, it contains the template, but not the updated values.
Should I make the create pdf step somehow wait for the updates to be saved?
Are you calling .saveChanges() anywhere in your script? (Before getting the blob.)
Not sure if this is required with sheets, but I had a similar issue in docs because I was not saving changes before getting the blob.
Edit:
Just tested with the following code and it appears that .saveChanges is not required:
function test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
sheet.getRange(1, 1, 1, 1).setValue("Test");
var file = DriveApp.getFileById(ss.getId());
var blob = file.getBlob().getAs('application/pdf');
DriveApp.createFile(blob);
}

Merging many spreadsheets into report file exceeds maximum execution time

I am using the following script to add rows of files from a student loop in the Google spreadsheet if credits are less than x. The script was working good but as the data in the spreadsheet is being added daily, now the script is throwing "Exceeded maximum execution time" error (we have more than 2000 files). As I am new to scripting I don't know how to optimize the code.
Could someone help me to optimize the code or any solution so that the execution time take less than 5 min. Every time you compare to an email, it has to be compared to many emails. Please Help!
function updated() {
//Final file data (Combined)
var filecombined = SpreadsheetApp.openById("XXXXXXXXXX");
var sheet2 = filecombined.getSheets();
//Folder with all the files
var parentFolder = DriveApp.getFolderById("YYYYYYYYYYYY");
var files = parentFolder.getFiles();
//Current Date
var fecha = new Date();
//Path for each file in the folder
while (files.hasNext()) {
var idarchivo = files.next().getId();
var sps = SpreadsheetApp.openById(idarchivo);
var sheet = sps.getSheetByName('STUDENT PROFILE');
var data = sheet.getDataRange().getValues();
var credits = data[5][1];
//Flat; bandera:1 (new row), bandera:2 (update row)
var bandera = 1;
//Take data from final file (Combined)
var data2 = sheet2[0].getDataRange().getValues();
//If credits are less than X: write
if (credits < 120) {
var email = data[2][1];
var lastrow = filecombined.getLastRow();
var u = 0;
//comparison loop by email, if found it, update and exit the loop
while (u < lastrow) {
u = u + 1;
if (email == data2[u - 1][1]) {
sheet2[0].getRange(u, 3).setValue(credits);
sheet2[0].getRange(u, 4).setValue(fecha);
u = lastrow;
bandera = 2;
}
}
//if that email does not exist, write a new row
if (bandera == 1) {
var nombre = data[0][1];
sheet2[0].getRange(lastrow + 1, 1).setValue(nombre);
sheet2[0].getRange(lastrow + 1, 2).setValue(email);
sheet2[0].getRange(lastrow + 1, 3).setValue(credits);
sheet2[0].getRange(lastrow + 1, 4).setValue(fecha);
}
}
}
SpreadsheetApp.flush();
}
The questioner's code is taking taking more than 4-6 minutes to run and is getting an error Exceeded maximum execution time.
The following answer is based solely on the code provided by the questioner. We don't have any information about the 'filecombined' spreadsheet, its size and triggers. We are also in the dark about the various student spreadsheets, their size, etc, except that we know that there are 2,000 of these files. We don't know how often this routine is run, nor how many students have credits <120.
getvalues and setvalues statements are very costly; typically 0.2 seconds each. The questioners code includes a variety of such statements - some are unavoidable but others are not.
In looking at optimising this code, I made two major changes.
1 - I moved line 27 var data2 = sheet2[0].getDataRange().getValues();
This line need only be executed once and I relocated it at the top of the code just after the various "filecombined" commands. As it stood, this line was being executed once for every student spreadsheet; this along may have contributed to several minutes of execution time.
2) I converted certain setvalue commands to an array, and then updated the "filecombined" spreadsheet from the array once only, at the end of the processing. Depending on the number of students with low credits and who are not already on the "filecombined" sheet, this may represent a substantial saving.
The code affected was lines 47 to 50.
line47: sheet2[0].getRange(lastrow+1, 1).setValue(nombre);
line48: sheet2[0].getRange(lastrow+1, 2).setValue(email);
line49: sheet2[0].getRange(lastrow+1, 3).setValue(credits);
line50: sheet2[0].getRange(lastrow+1, 4).setValue(fecha);
There are setvalue commands also executed at lines 38 and 39 (if the student is already on the "filecombined" spreadsheet), but I chose to leave these as-is. As noted above, we don't know how many such students there might be, and the cost of these setvalue commands may be minor or not. Until this is clear, and in the light of other time savings, I chose to leave them as-is.
function updated() {
//Final file data (Combined)
var filecombined = SpreadsheetApp.openById("XXXXXXXXXX");
var sheet2 = filecombined.getSheets();
//Take data from final file (Combined)
var data2 = sheet2[0].getDataRange().getValues();
// create some arrays
var Newdataarray = [];
var Masterarray = [];
//Folder with all the files
var parentFolder = DriveApp.getFolderById("YYYYYYYYYYYY");
var files = parentFolder.getFiles();
//Current Date
var fecha = new Date();
//Path for each file in the folder
while (files.hasNext()) {
var idarchivo = files.next().getId();
var sps = SpreadsheetApp.openById(idarchivo);
var sheet = sps.getSheetByName('STUDENT PROFILE');
var data = sheet.getDataRange().getValues();
var credits = data[5][1];
//Flat; bandera:1 (new row), bandera:2 (update row)
var bandera = 1;
//If credits are less than X: write
if (credits < 120){
var email = data[2][1];
var lastrow = filecombined.getLastRow();
var u = 0;
//comparison loop by email, if found it, update and exit the loop
while (u < lastrow) {
u = u + 1;
if (email == data2[u-1][1]){
sheet2[0].getRange(u, 3).setValue(credits);
sheet2[0].getRange(u, 4).setValue(fecha);
u = lastrow;
bandera = 2;
}
}
//if that email does not exist, write a new row
if(bandera == 1){
var nombre = data[0][1];
Newdataarray = [];
Newdataarray.push(nombre);
Newdataarray.push(email);
Newdataarray.push(credits);
Newdataarray.push(fecha);
Masterarray.push(Newdataarray);
}
}
}
// update the target sheet with the contents of the array
// these are all adding new rows
lastrow = filecombined.getLastRow();
sheet2[0].getRange(lastrow+1, 1, Masterarray.length, 4);
sheet2[0].setValues(Masterarray);
SpreadsheetApp.flush();
}
As I mentioned in my comment, the biggest issue you have is that you repeatedly search an array for a value, when you could use a much faster lookup function.
// Create an object that maps an email address to the (last) array
// index of that email in the `data2` array.
const knownEmails = data2.reduce(function (acc, row, index) {
var email = row[1]; // email is the 2nd element of the inner array (Column B on a spreadsheet)
acc[email] = index;
return acc;
}, {});
Then you can determine if an email existed in data2 by trying to obtain the value for it:
// Get this email's index in `data2`:
var index = knownEmails[email];
if (index === undefined) {
// This is a new email we didn't know about before
...
} else {
// This is an email we knew about already.
var u = ++index; // Convert the array index into a worksheet row (assumes `data2` is from a range that started at Row 1)
...
}
To understand how we are constructing knownEmails from data2, you may find the documentation on Array#reduce helpful.

How to write Google Sheets Script that searches my drive files for a variable search term entered in Cell B1 of my sheet?

I'm trying to write a google sheets script to search a series of my Drive files for a variable search term. My code works well as long as I consistently entitle my files that I want to search with "Joshs File". But I want to be able to search fullText by a variable search term entered in cell B1 of my sheet. What syntax do I use to do that?
fullText contains WHAT???
function SearchFiles() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var sh0 = sheet.getSheets()[0];
var search0 = sh0.getRange("B1").getValue();
//Please enter your search term in the place of Letter
var searchFor = 'title contains "Joshs File"' + 'and fullText contains "X"';
var names =[];
var fileIds=[];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var name = file.getName();
names.push(name);
}
for (var i=0;i<names.length;i++){
Logger.log(names[i]);
}
var body = Logger.getLog();
var range=sh0.getRange("A5");
range.setValue(body);
}
Try using implementing this code:
function SearchFiles(){
var textString = "Sample";
var files = DriveApp.getFolderById(FolderID).searchFiles(
'fullText contains "'+textString+'"');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
}
Just like how you concatenate a variable and string in JavaScript you have to use "+" in order for it to be recognized as a variable.
Hope this helps.

XPages - unsorted Dojo Data Grid opens incorrect document

I'm using a Dojo Data grid together with a REST service to display view data. When I double click on a row, an XPage is opened. My problem is that, if one of the columns in the grid is not sorted, the wrong XPage is opened. What could be the problem here?
<xe:djxDataGrid id="P_Alle_DDG" store="restService2"
styleClass="DojoViewTable" title="Pendenzen - Alle" autoHeight="20"
rowsPerPage="25" selectable="true" selectionMode="multiple"
singleClickEdit="true" rowSelector="2" style="font-size:12pt"
escapeHTMLInData="true">
<xe:this.onRowDblClick><![CDATA[var idx = arguments[0].rowIndex;
var unid = restService2._items[idx].attributes["#unid"];
var url = 'Reparatur.xsp?documentId='+unid+'&action=openDocument';
window.document.location.href = url;]]></xe:this.onRowDblClick>
UPDATE: With the following JavaScript code the problem has been solved:
var grid = arguments[0].grid;
var index = arguments[0].rowIndex;
var item = grid.getItem(index);
var unid = item.attributes["#unid"];
var url = 'Reparatur.xsp?documentId='+unid+'&action=openDocument';
window.document.location.href = url;
Tony, try this method of opening the document. The code if very similar to yours, but the key difference is that I made a view column that contains the unid, I called it "docid". This works for me.
var grid = arguments[0].grid;
var index = arguments[0].rowIndex;
var item = grid.getItem(index);
var unid = item["docid"];
var url = "New_PO.xsp?doc=" + unid;
window.document.location.href = url;