Google Sheets - getData() returns an error as not defined - sql

So i am using the following code to copy a query into a spreadsheet. When i run the code it gives me ReferenceError: getData is not defined.
if i try the same code on another google sheets document it runs smoothly and copies everything
function importdataNPS() {
let data = getData("https://popsql.com/share/queries/···/last_run.csv?access_token=...");
let sheet = SpreadsheetApp.openById('·····').getSheetByName('Real_NPS_Q4');
sheet.getRange(2,1,sheet.getLastRow(),data[0].length +1).clearContent();
if ( data.length == 0){ return; }
sheet.getRange(1,1,data.length,data[0].length).setValues(data);
}
What am I doing wrong? is there an authorization for the google sheet?

Related

How do I print the output of google sheets script back to google sheet?

I am trying to use an api for verifying phone numbers and emails for the database I want to create in google sheets. I coded the following on app scripts of sheet.
function phone(phno) {
var response = UrlFetchApp.fetch("https://neutrinoapi.net/phone-validate?user-id=USERNAME_HERE&api-key=API_KEY_HERE&number="+phno+"&country-code=IN")
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data["valid"]);
Logger.log(data["prefix-network"]);
Logger.log(data["type"]
}
The json returns a bunch of things, valid = true\false {If the number is valid}; prefix-network = service_provider; type = mobile\landline etc.
The idea is that if I call = phone(D2) in cell E2 for example, where D2 stores a valid phone number, I want the validity to be shown in E2, which is a boolean of true\false for if the phone number is valid or not. I would also love to show the next 2 columns with prefix-network and type. But they aren't necessarily essential, just desirable.
The API works fine, and I can see the output in the execution logs in App Scripts, and it's correct with a few test data I tried. However, I cannot find any way to display the result back in the sheet in cell E2. The code has to be generic such that if I drag the code for the cell, it should return the output to the subsequent cells.
I hope the question is clear and the code is sufficient to explain it.
Looking forward to the replies.
Thanks in advance for the help!!
Something like this:
function phone(phno) {
var response = UrlFetchApp.fetch("https://neutrinoapi.net/phone-validate?user-id=USERNAME_HERE&api-key=API_KEY_HERE&number="+phno+"&country-code=IN")
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data["valid"]);
Logger.log(data["prefix-network"]);
Logger.log(data["type"]
const sh = SpreadsheetApp.getActiveSheet();
sh.getRange(1,1,1,3).setValues([[data["valid"],data["prefix-network"],data["type"]]]);
}

Cannot read property 'getDataRange' of null [duplicate]

This question already has an answer here:
How to fix 'TypeError: Cannot call method "getRange" of null' in Google Apps Script
(1 answer)
Closed last year.
Im very new working with google script and APIs and Im trying to run a piece of code that makes the sheet in to a Json however I`m facing an issue where it says:
TypeError: Cannot read property 'getDataRange' of null
json # Code.gs:4
The code I`m using is the following:
function json() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
const sheet = spreadsheet.getSheetByName("APItest")
const data = sheet.getDataRange().getValues()
const jsonData = convertToJson(data)
return ContentService
.createTextOutput(JSON.stringify(jsonData))
.setMimeType(ContentService.MimeType.JSON)
}
I already tried to change the getSheetID but also didn`t work
Probably you're getting null value after the execution of
const sheet = spreadsheet.getSheetByName("APItest")
And That's why you get the error in the next statement. make sure that the sheet is not null.

Requesting a BigQuery API from Google Spreadsheet generates an Error

I am trying to fetch data from Bigquery and show them into my spreadsheet using the App script. First, I created a Spreadsheet file in my G-drive and then put my code into the script editor.
Here is the code I have used to get all the datasets from Bigquery:
function getAllDataSets(filter){
try{
let req_for_datasets = BigQuery.Datasets.list(PROJECT_ID);
let datasets = req_for_datasets.datasets;
let list = [];
datasets.forEach( obj => {
if(obj.datasetReference.datasetId.indexOf(filter)>-1)
list.push(obj.datasetReference.datasetId);
});
return list;
}catch(e){
return [];
}
}
this script works fine and I can see the result while running my script through Code Editor. I try to use this script in onOpen() or onEdit() to be able to get data when the spreadsheet gets opened.
but using the spreadsheet I receive this message:
GoogleJsonResponseException: API call to bigquery.tables.list failed with error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.
this is the code I have put in onOpen function:
function onOpen(){
let ui = SpreadsheetApp.getUi();
let method_list = ["SUM", "AVG", "COUNT"];
//Adding a Custom menu
ui.createMenu("Media Budget")
.addItem("Facebook", "makeQuery")
.addSeparator()
.addItem("Google Ads", "makeQuery")
.addToUi();
//Getting all datasets from the specified project
let dataset_list = getAllDataSets("dw_sandbox_");
Browser.msgBox(dataset_list);
//Creating dropdown list cell
let cell = SHEET.getRange("B1");
applyValidationToCell(dataset_list, cell);
}
other than that if I try to execute the function using the custom menu in the spreadsheet everything works fine as well.
It would be really appreciated if you can help me.
If you can perform a request when running code manualy, but not on simple onOpen or onEdit trigger - the reason is authorization issues
See restrictions:
Because simple triggers fire automatically, without asking the user
for authorization, they are subject to several restrictions:
...
They cannot access services that require authorization. For example, a
simple trigger cannot send an email because the Gmail service requires
authorization, but a simple trigger can translate a phrase with the
Language service, which is anonymous.
Workaround
Option a)
Rather than running the request onOpen, implement it into a separate function that will be called when chosen from custom menu
Sample:
function onOpen(){
let ui = SpreadsheetApp.getUi();
let method_list = ["SUM", "AVG", "COUNT"];
//Adding a Custom menu
ui.createMenu("Media Budget")
.addItem("Facebook", "makeQuery")
.addSeparator()
.addItem("Google Ads", "makeQuery")
.addSeparator()
.addItem("bigQuery", "makeBigQuery")
.addToUi();
}
function makeBigQuery(){
//Getting all datasets from the specified project
let dataset_list = getAllDataSets("dw_sandbox_");
Browser.msgBox(dataset_list);
//Creating dropdown list cell
let cell = SHEET.getRange("B1");
applyValidationToCell(dataset_list, cell);
}
Option b)
Run your exisitng code on installable instead on simple trigger.
Installable triggers can run funcitons that reuire auhtorization
To convert your simple trigger into an installable
rename the function from onOpen (otherisw you might run into conflicts from having both simple and installable triggers run simultaneously)
Go on Edit -> Current project's triggers - > New trigger - see also here

Google Apps Script copying data to wrong sheet

I am using this code which is supposed to copy data from "REQUEST" sheet to "MASTER" sheet but actually the code copies data to "MASTER" sheet as well as some other sheet also in the file.
function onFormSubit () {
var app = SpreadsheetApp;
var ss = app.getActiveSpreadsheet();
var shtForm = ss.getSheetByName("REQUEST");
var shtAgrt = ss.getSheetByName("MASTER");
var rcrdCount = shtAgrt.getRange(1, 25).getValue();
var chkNum = shtForm.getRange(Math.max(shtForm.getLastRow(),2),1).getValue();
shtAgrt.getRange(rcrdCount+1, 2).setValue(chkNum);
}
I don't want the code to copy data to any other sheet.
I don't understand what happened but error is gone away now. Perhaps it went away after deleting all form submit data or after refreshing google sheet.

Auto Update specified tab in Google spreadsheet from Web via script

I am currently trying to pull in data from a website into my Google Sheet, however, it will automatically pull the data on whatever tab I am on when the sheet updates.
The script I currently have is below. I have 5 tabs in the workbook and the tab I need updated is labeled 'Update' and is the 3rd tab in the workbook.
The data currently pulls in correctly, however, it will not only update the tab I need updated.
function getData() {
var queryString = Math.random();
var cellFunction = '=IMPORTHTML("http://www.golfchannel.com/tours/pga-tour/2017/us-open/?' + queryString + '","table",2)';
SpreadsheetApp.getActiveSheet().getRange('A1').setValue(cellFunction);
}
Change your code line to this:
SpreadsheetApp.getSheetByName('Update').getRange('A1').setValue(cellFunction);
You can set the sheet by calling the method getSheetByName().
Returns a sheet with the given name. If multiple sheets have the same name, the leftmost one is returned. Returns null if there is no sheet with the given name.
Here is a sample snippet:
function myFunction() {
var sss = SpreadsheetApp.openById('FILEID'); // sss = source spreadsheet
var ss1 = sss.getSheetByName('Sheet1');
var ss2 = sss.getSheetByName('Sheet2');
var source_range = ss1.getRange("A1:G10");
var target_range = ss2.getRange("A1:G1");
source_range.copyTo(target_range);
}
Hope this helps.