Accessing spreadsheet in Google Script - javascript

I am writing a google script on top of a spreadsheet.
I want to deploy it as a web app.
It shows some values.
Unfortunately, with my current code, google reminds me:
TypeError: Cannot call method "getSheetByName" of null.
I have no idea where the mistake is.
Here's the code
function doGet(e) {
var app = UiApp.createApplication().setTitle('Details');
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
var dataFromCell = ss.getRange("B4").getValue();
var mypanel = app.createVerticalPanel();
var label = app.createLabel(dataFromCell);
app.add(mypanel);
app.add(label);
return app;
}

In standalone webapps you cannot use getActiveSpreadsheet because no one is using it actively...
Use SpreadsheetApp.openById('ID') instead, you can get the ID in the url of your spreadsheet like in this example :
https://docs.google.com/spreadsheet/ccc?key=0AnqSFd3iikE3d-------nZIV0JQQ0c1a3dWX1dQbGc#gid=0
between key= and #, ie 0AnqSFd3iikE3d-------nZIV0JQQ0c1a3dWX1dQbGc

Not need to use ID , just try this code ( change mygooglelocation with your Spreadsheet name and range of cells. Working very well for me with google maps...
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('mygooglelocation');
var ss = SpreadsheetApp.getActive();
var mylocationInfo = ss.getRange("A2:B4").getValues();

Related

Importrange from multiple URLs using Apps Script

I am a newbie for coding and GAS. I can solve the issue via google spreadsheet quite well, but I am looking for better and efficient ways to solve the problem via GAS.
This is the script I wrote so far.
function myFunction() {
const app= SpreadsheetApp;
const activeSheet = app.getActiveSpreadsheet().getActiveSheet();
const temp = activeSheet.getRange("AE4:AE").getValues();
}
As you can see it from a picture, there are URLs and each URL contains a value which need to be pulled out. I want to importrange values from cell "C6" from each URL and print it to the left column. Key to this problem is that one value needs to be imported from each URL to the left.
Google SpreadSheet
= IMPORTRANGE("URL", "Sheet1!C6")
Puts data in the active cell from Sheet1!C6
function myfunk() {
const ss = SpreadsheetApp.getActive();
const cell = ss.getActiveCell();
cell.setValue(ss.getRange("Sheet1!C6").getValue())
}
Note: this is not a custom function...not meant to be run by placing in cell of spreadsheet.

Google script for Alphavantage gives weird results

I am trying to make a google script which i want to use in Google sheets.
I followed a tutorial video on youtube and i had the idea that my script was working well.
But then two strange things happen, and i can't figure out why.
Below is my code, this code is exactly doing what i want.
It is showing the EPS of IBM in the google sheets and also in the log.
However the moment i change the APIkey from "demo" to my own APIkey it is not working anymore.
At that moment it is still showing the EPS in the LOG, but i will get an empty cell in Google Sheets.
I have no idea why that happens.
/**
* Imports api data from alphavantage
* #customfunction
*/
function apiav(a) {
var res = UrlFetchApp.fetch(
'https://www.alphavantage.co/query?function=OVERVIEW&symbol=IBM&apikey=demo'
);
var content = res.getContentText();
var json = JSON.parse(content);
var overviewvalue = json['EPS'];
Logger.log(overviewvalue);
return overviewvalue;
}
Try adding {validateHttpsCertificates: false} to your UrlFetchApp.fetch() to ignores any invalid certificates for HTTPS requests.
Your code should look like this:
function apiav(a) {
var res = UrlFetchApp.fetch('https://www.alphavantage.co/query?function=OVERVIEW&symbol=IBM&apikey=ABCDEFGH', {validateHttpsCertificates: false});
var content = res.getContentText();
var json = JSON.parse(content);
var overviewvalue = json['EPS'];
Logger.log(overviewvalue);
return overviewvalue;
}
Output:
Reference:
UrlFetchApp

Google Apps Script returning a null

I have a google apps script function that is pulling data from a spreadsheet. It is able to log the information happily and then I return the data to a javascript function. But when I try to stringify and alert the information it alerts "null".
Not sure where I am going wrong!
Javascript calling the GAS function:
google.script.run.withSuccessHandler(getNews).getTheNews();
GAS function:
function getTheNews(){
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("NewsFeed");
var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
Logger.log(theNews);
return theNews;
}
The GAS log:
Javascript function receiving the info:
function getNews(theNews){
var mystr = JSON.stringify(theNews);
alert(mystr);
}
Issue and workaround:
Unfortunately, it seems that in the current stage, the date object cannot be directly returned from Google Apps Script side to Javascript side. Also I could replicate your situation. I think that this is the reason of your issue. So as the current workaround, how about the following modification?
Modified script:
In this modification, the date object is converted to the string and sent to Javascript side. At Javascript side, the date string is converted to the date object.
HTML & Javascript side:
google.script.run.withSuccessHandler(getNews).getTheNews();
function getNews(theNews){
theNews = theNews.map(r => r.map(c => new Date(c))); // Added
var mystr = JSON.stringify(theNews);
alert(mystr);
}
Google Apps Script side:
function getTheNews(){
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("NewsFeed");
var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
return theNews.map(r => r.map(c => c.toISOString())); // Modified
}
I think that in this case, c.getTime() instead of c.toISOString() can be also used.
Note:
For example, if you want to retrieve the display values on the cells, you can also modify as follows. In this case, Javascript is not required to be modified.
From
var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getValues();
To
var theNews = ws.getRange(3, 2, ws.getLastRow()-2, 1).getDisplayValues();
Also I found this issue at the Google issue tracker. Ref But when I saw the status, it seems "Won't Fix (Intended behavior)".
References:
toISOString()
getDisplayValues()

how to onFormSubmit(), two separate google source spreadsheets?

I have two google separate forms that submit new client data to two separate spreadsheets. How would I use the onFormSubmit() on two separate spreadsheet sources in one app script editor? thank you all very much :D
if this is getting one sheet how could it implement two or more?
i think i get SpreadsheetApp.getSheetByName('xyz');
and im a little unsure exactly what an active sheet is or activated I think it is the sheet you're currently on in the spreadsheet the dev app script is being derived from. I might be missing some other basic concepts
function onFormSubmit(){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sht = ss.getSheetByName('New Client Submission Form (Phone)'&&'New Client Submission Form (Emailed)')
var activeRng = sht.getRange("A2:K2")
var values = activeRng.getValues()
var height = values.length
var width = values[0].length
var ss_dest = SpreadsheetApp.openById('1wgzUSXFNLFQz6tv42Cp_o94qRPAB9IkZnKP5tGL003o')
var sht_dest = ss_dest.getSheetByName('Estimate Compiler')
var destRange = sht_dest.getRange(2,1,height,width)
destRange.setValues(values)
}
this function does exatly as expected I just don't know how to implement two or more yet
function onFormSubmit(e) {
var formObj={LinkedSheet1:FormName1,LinkedSheet2:FormName2};//you provide this from a knowledge of the connection between the form and linked sheet
var form=formObj[e.range.getSheet().getName()];//this returns the form for each sheet
switch (form) {
case 'FormName1':
//code for FormName1
break;
case 'FormName2':
//code for FormName2
break;
}
}
onFormSubmit Event Object

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);

Categories

Resources