Auto Update specified tab in Google spreadsheet from Web via script - google-sheets-api

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.

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"]]]);
}

How to edit cell Values

I'm new to the google spreadsheets API node module. I'm asking on how to edit the cell value of a sheet. I have tries following other internet videos to do it but none of them work. I have a variable called doc that is the spreadsheet and the sheet itself is called SheettoUse.
const doc = new GoogleSpreadsheet('CODE');
await doc.useServiceAccountAuth({
client_email: creds.client_email,
private_key: creds.private_key,
});
await doc.loadInfo(); // loads document properties and worksheets
const TicketASheet = doc.sheetsByTitle['Ticket-A']; // or use doc.sheetsById[id]
let sheet = TicketASheet
await sheet.loadCells('A1:AAA1000');
let cells = sheet.getCell(0,0)
console.log(cells.value)
Thanks,
William
.setValue() is used to update cell value in Apps Script.
To set cell value in npmjs, You can refer to the following sample code:
// update cell value
cells.value = 123.456;
// update cell formula
cells.formula = '=A1';
// update cell format
cells.textFormat = { bold: true };
// update cell note
cells.note = 'This is a note!';
await sheet.saveUpdatedCells(); // saves changes in the cell
Reference:
google-spreadsheet
GoogleSpreadsheetCell

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.

How to get list of sheets id(s) from specific SpreadSheet with Google Sheets API?

i can put data in the cell,
i can CopyTo to make new sheet from existing sheet.
but when i want to delete several sheets, i need list of sheet id(s)
but i don't know how to get the list of sheet id(s) from speadsheet?
does somebody know how to do it?
The following function will display all sheet names and id's for the active spreadsheet.
function getSheetId()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var allSheets=ss.getSheets();
var ids=[];
for(var i=0;i<allSheets.length;i++)
{
ids[allSheets[i].getName()]=allSheets[i].getSheetId();
}
var s='<table width="100%">';
for(key in ids)
{
s+=Utilities.formatString('<tr><td><strong>Sheet Name</strong></td><td>%s</td><td><strong>Sheet Id</strong></td><td>%s</td></tr>',key,ids[key]);
}
s+='</table>'
var userInterface=HtmlService.createHtmlOutput(s).setWidth(800).setHeight(450);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Sheet Keys for Spreadsheet: ' + ss.getName())
}

What is the correct trigger for activating a google sheets script, when a user submits data into a connected form?

I have attached the following script to a Google spreadsheet, so the user gets a notification when submitting a form. When I run it in script editor, it works, but when I submit data in the actual live form attached to the spreadsheet, it doesn't.
I've tried all triggers for running the script but I've received no emails.
here is the code:
function sniffEmailAddress(){
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
// get email
var dataRangeEmail = sheet.getRange(lastRow, 3 ); // 3 is the email col
var emailAddress = dataRangeEmail.getValue();
// get names
var dataRangeFName = sheet.getRange(lastRow, 2 ); // 3 is the fName col
var fName = dataRangeFName.getValue();
// get messege
var dataRangeMessege = sheet.getRange(lastRow, 4 ); // 3 is the Messege col
var message = dataRangeMessege.getValue();
// Log
Logger.log(emailAddress);
var message = "Hi "+fName+", \nThanks for contacting us. You will be contacted shortly.\n Your messege: \n"+message;
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
}
The trigger should be From Spreadsheet > on Form submit.
Thanks All,
I think I found the reason. It seems I should have declared an event object in my function.
function sniffEmailAddress(evtObj){....}
Not sure but I think this fixed it.
Regards,
CBRCODER