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 {}}}
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);
}
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.
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.
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;