Fill fields in template from google sheet - javascript

I am trying to use a Google Apps Script to populate fields in Google Slides from Google Sheets. I found a code online that appears to be popular to accomplish this, however, I continue to get errors that are not cited as common errors in the comments or other bodies of information.
Here is the code:
function fillTemplate() {
var Presentation_ID= "PRESENTATION URL";
var Presentation=SlidesApp.openById(Presentation_ID);
var values= SpreadsheetApp.getActive().getDataRange().getValues();
values.forEach(function(row){
var templateVariable= row[0];
var templateValue= row[1];
Presentation.replaceAllText(templateVariable, templateValue);
});
}
I have attempted to populate the sheet URL and the range as follows:
var values= SpreadsheetApp.getActive(SHEET URL).getDataRange(FIRSTCELL:LASTCELL).getValues();
The error message is as follows:
Execution log
11:04:27 AM Notice Execution Started.
11:04:30 AM Error. Exception: The match text should not be empty
(anonymous) # Code.gs:10
fillTemplate # Code.gs:7
For what it's worth, my cell range is C49:D60, but I have tried to move it to a separate sheet altogether with A1:B12

Related

Sending table charts from google spreadsheet to slack using apps script

I'm trying to send table charts on a daily basis to my slack channel from my google spreadsheet. The automation works when I am creating some normal charts - e.g. column charts or line charts - but it shows an error if I try the same thing with a table chart. Should I change any of my code to have this running?
function myFunction(){
var sheetUrl2 = "https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxxx/edit#gid=xxxxx"
var ss2 = SpreadsheetApp.openByUrl(sheetUrl2);
var sheet2 = ss2.getSheetByName("MyDailySheet");
var charts2 = sheet2.getCharts();
var chartImage2 = charts2[0].getBlob().getAs('image/jpeg').setName("graph.png");
sendSlack(chartImage2);
}
function sendSlack(chart){
var url = 'https://slack.com/api/files.upload';
var token = 'xoxp-xxxxxxxxxxxxxxxxxxxxxxxxxx';
var channel = '#general';
var payload = {
'token' : token,
'channels' : channel,
'file' : chart,
'filename' : 'DailyUsers - Last 30 Days'
};
var params = {
'method' : 'post',
'payload' : payload
};
var response = UrlFetchApp.fetch(url, params);
}
Error message:
Exception: Service Spreadsheets failed while accessing document with id xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
myFunction # DailyChart02.gs:7
This code works perfectly and sends a chart to my slack channel.
My slack app has these token scopes authorized: (bot) chat:write chat:write.public files:write (User) chat:write files:write
My table chart looks something like this. It shows perfectly on my spreadsheet file.
Issue and workaround:
I have had the same situation with you. In the current stage, it seems that the table chart cannot be directly retrieved as the image blob. This might be the current specification. So as a current workaround, I would like to propose the following flow. In this workaround, Google Slides is used as a wrapper. By the way, in your script, getAs('image/jpeg') is used. But it seems that setName("graph.png") is used. So in this modification, the mimeType uses image/png from the filename.
Retrieve the table chart from Google Spreadsheet.
Create new Google Slides as a temporal file.
Insert the table chart from Google Spreadsheet to Google Slides.
Retrieve the inserted chart on Google Slides as an image blob.
Remove the temporal Google Slides.
Use the blob to the Slack API.
By this flow, the table chart can be retrieved as the image blob. When your script is modified, it becomes as follows.
Modified script:
Please modify myFunction() as follows.
function myFunction(){
var sheetUrl2 = "https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxxx/edit#gid=xxxxx"
var ss2 = SpreadsheetApp.openByUrl(sheetUrl2);
var sheet2 = ss2.getSheetByName("MyDailySheet");
var charts2 = sheet2.getCharts();
// --- I added below script.
var s = SlidesApp.create("temporalSlides");
var chartImage2 = s.getSlides()[0].insertSheetsChartAsImage(charts2[0]).getBlob().setName("graph.png");
DriveApp.getFileById(s.getId()).setTrashed(true);
// ---
sendSlack(chartImage2);
}
Note:
In this case, how about reporting it to Google issue tracker as the future request? Ref
Reference:
insertSheetsChartAsImage(sourceChart)

cannot get value from google sheet through app script

I'm starting to learn how to code with Google App script and just completed the codelab playlist on Extending Google Sheets.
So to try it out I wrote a code with the intention of pulling a value from a specific cell from a sheet through a variable calles "OrderNum", using Logger to log the variable that would contain this value to check my code, but for some reason I keep getting an "(variable) is not defined)" error and I've tried multiple things already and nothing works... what I am doing wrong?? Here is my code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Create a custom menu
ui.createMenu('Order Functions')
.addItem('Copy form to database',"copy2db")
.addToUi();
}
// Pull orderNum value from sheet
function checkOrderNum() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var orderNum = sheet.getRange('H2').getValue();
}
Logger.log('var ', orderNum);
snippet of google sheet showing value of cell H2
The error I'm getting is "ReferenceError: orderNum is not define). I don't get it, it seems to me that all the references are there. Also when I remove the logger command, no error appears but then I have no idea if my code is correct, which apparently isn't.
Thanks for the help,
Nestor
You are getting an error message : "ReferenceError: orderNum is not define).
This is because your Logger statement is not part of a function.
Logger is a feature of Google scripts and Logger.log is well documented.
In the following example, I have included three versions of a Logger statement.
Logger.log("the order number is "+orderNum);: in this case the description text is in quotes, followed by the "+" operator and the variable name.
Logger.log('var %s', orderNum);: the suggestion made by #Tanaike. In the case, '%s' acts as a placeholder doc ref.
Logger.log('var ', orderNum);: this is your logger statement, but this time it is included within the function.
These statements return these results:
the order number is 1001
var 1001.0
var 1001.0
// Pull orderNum value from sheet
function checkOrderNum() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var orderNum = sheet.getRange('H2').getValue();
Logger.log("the order number is "+orderNum);
Logger.log('var %s', orderNum);
Logger.log('var ', orderNum);
}

ReferenceError: "sheet" is not defined

It is my first time to develop the google script for my google sheet
Here is the code of my script
function doGet(e) {
var url = 'https://docs.google.com/spreadsheets/d/1p3fW0Vkx89tdiws3Z-a5_LpLwyGYj7pacIek3f9Z96w/edit#gid=1862590156'
var name = '無標題表單 (回應)'
var SpreadSheet = SpreadsheetApp.openByUrl(url);
var values = sheet.getSheetValues(1, 1, 1, 1);
Logger.log(values);
}
When I run the script,and then it show the message "ReferenceError: "sheet" is not defined. (第 7 行,檔案名稱:巨集)"
I try to use the method in this article ReferenceError: "Sheets" is not defined but still cannot work.
Thank you!
tl;dr
Change var SpreadSheet to var sheet in the provided code.
As the error message is explaining: The variable sheet is not defined in the provided code.
This means at the point where sheet is trying to be used, it does not exist yet. It will have to be defined first.
Try running one of the following before you use the variable sheet
var sheet = SpreadSheet.getSheetByName('YourSheetName');
or using .openByUrl
var sheet = SpreadsheetApp.openByUrl(url);

Removing Edit Access from a Sheet using email from a cell

I am trying to figure out how to remove someone from a spreadsheet using google app scripts.
Essentially, I have a central spreadsheet with information such as emails, names, UID's etc on it. I am trying to pull the email from this spreadsheet and use the removeEditor function to remove that email from another spreadsheet. You can view the code below.
var officerIDrow = officerID + 1;
var Tracker = SpreadsheetApp.getActive().getSheetByName('P_Tracker'); //the button is on the same sheet as this, this is why it is get active.
var PTBooking = SpreadsheetApp.openById("1JPS69ko99dQTEwjplF_l2l2G_T8RyHjxCyMxXd_AV_s"); //Referring to the other sheet where the email will be removed from editors.
var EmailAddressRange = "F" + officerIDrow; //This is the column where the emails are stored. The officer ID row refers to the user inputted value in a dialog. Don't worry about this, I have already checked to see if this is the issue,
var EmailAddress1 = Tracker.getRange(EmailAddressRange);
var EmailAddress2 = EmailAddress1.getValue();
var EmailAddress3 = Utilities.formatString(EmailAddress2); //In my desperation, I was trying to see if setting it as string would help.
PTBooking.removeEditor(EmailAddress3);
This isn't the full version of the code. If you'd like to see it, you can click here. But all that matters is above, everything else works fine.
The code above runs fine until it hits the last line where it tries to remove the email. The error message that appears says: "Invalid email: ". I'm assuming after the "email:" bit, it should display what has been pulled. But it doesn't! I have no idea why it isn't finding and using the email to remove people.
Can anyone spot any issues?
Thanks,
Shaun.
This basic test worked for me. It could read email address from the spreadsheet then remove editors from the external sheet. I tried to copy your example, but I don't know how the officerIDrow works, but I assume it's a number. So just stored a number as a var
function myTest() {
var ss = SpreadsheetApp.openById("ID HERE");
var idRow = 11;
var tracker = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("tracker");
var emailCell = "F"+idRow;
Logger.log(emailCell);
var emailAddress = tracker.getRange(emailCell).getValue();
Logger.log(emailAddress);
ss.removeEditor(emailAddress);
var editors = ss.getEditors();
Logger.log(editors);
}
I've left the Logger bits in as it will help point you at what script is doing at each point.
The email address in the cell must be plain, such as google#google.com

Google Apps Scripts - Extract data from gmail into a spreadsheet

this is the first script i try to write from scratch. It's been no good up to now so i'm going to ask for some help.
Case: I recieve e-commerce confirmation emails from e-commerce sites no reply email address. In the email's body they send email address from buyers. I want to send an automated mail to the body's email address.
How i plan to do this (any suggetions to eliminate steps will be thanked).
Use a rule to tag incoming emails with a unique tag.
Use that tag to identify emails in gmail with a script, go one by one and extract the info i need. Use regex with the emails body content to extract the email address i need to send the automated emails. Plan is to get: subject, date, email from body.
Write all that info to a spreadsheet.
Get rid of unique tag info to prevent duplicate runs.
Then use form mule addon to send emails from the spreadsheet.
So far, i've dealt with steps 1 (easy), and been stuggling with steps 2 and 3 (im not a coder, i can read, undestrand and hack. writing from scratch is a completely different thing). Ive dealt with 4 before i think this is the best way to deal with it.
With the script i extract info to the spreadsheet, with the addon i use the info from the spreadsheet to send emails.
This is the code ive written so far. I've left the regex part for later cause i cant even write anything into the spreadsheet yet. once i get that working, ill start working in the regex and "remove the label" aspects of the script.
function myFunction() {
function getemails() {
var label = GmailApp.getUserLabelByName("Main tag/subtag");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
var messages=threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var message=messages[j];
var subject=message.getSubject();
tosp(message);
}
}
}
function tosp(message){
var body=message.getBody()
var date=message.getDate();
var subject=message.getSubject();
var id= "my spreasheet id";
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getActiveSheet();
sheet.appendRow(subject,date,body);
}
}
Any help would be appreciated.
Thanks
Sebastian
Following is the code I wrote and tested that performs the steps 2, 3 and 4 mentioned by you perfectly well.
function myFunction() {
var ss = SpreadsheetApp.getActiveSheet();
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
for (var i=0; i<threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++)
{
var msg = messages[j].getBody();
var sub = messages[j].getSubject();
var dat = messages[j].getDate();
ss.appendRow([msg, sub, dat])
}
threads[i].removeLabel(label);
}
}
One of the faults in your code was that the appendRow function accepts an array of elements specified within [ ] brackets.
Depending on where you're attaching this script, your line of code:
var ss = SpreadsheetApp.openById(id);
is not necessary if the script is being written in the script editor of the Spreadsheet where you want these emails to be logged. However, if there are multiple sheets in that spreadsheet, you can replace my line
var ss = SpreadsheetApp.getActiveSheet();
by
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
Another suggestion is that the current code will give you messages in HTML format. Hence, if you want to get the message in plain text as you see it, use:
var msg = messages[i].getPlainBody();
Now you can write another function for regex and pass the message msg to that. Hope this helps!
I made a ready-to-use script, explaining how to use it (from the start) as well, for those who need more assistance.
It's on gmail-to-google-sheets-script repository. Just read the content and follow the instructions.
How to use
Create a new Google Sheet
Access menu Tools > Script Editor
Copy the content from gmailt-to-sheets.gs to editor, replacing the sample code there
Replace the value on SEARCH_QUERY to your real query (Do your search on gmail first, copy and paste the search terms there)
Select saveEmails on menu (near "run" and "debug" buttons)
Click on "Run" button
It will ask for authorization at first run, proceed accepting it (it's your Gmail account authorizing your Google Script account)
After run, the results will be applied to you sheet
Changing fields
If you want to save different message attributes, take a look at gmail-message class and change your script file the code below comments with a ✏️ (pencil).

Categories

Resources