Google Sheets Apps Script 'Unknown Function' - javascript

I created a script in Google Sheets Apps Script to call the Google Maps API, but the function is not recognized in the spreadsheet:
Below is the code I am using:
function mapAddress(input) {
var API_KEY = 'XXXXXXX';
var url = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?query=' +
input + '&key=' + API_KEY;
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
obj = JSON.parse(json);
addr = obj.formatted_address;
return addr;
}
I am using Chrome on Mac OS 11.6
I was expecting I'd be able to use a custom function in my spreadsheet, but when I try to use it, it returns a blank value.

Related

Export two pages of a spreedsheet

I want export two pages of a same spreedsheet to one single file, how can i do it?
var ssID = "ssID"
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx&gid=AAAA";
var url2 = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx&gid=BBBB";
var params = {method:"GET", headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url, params);
DriveApp.createFile(response).setName(name);
I believe your goal is as follows.
You want to select 2 of all sheets in a Google Spreadsheet and export it as one XLSX file using Google Apps Script.
In this case, how about the following sample script?
Sample script:
function myFunction() {
var name = "sample.xlsx"; // Please set the output filename.
var ssID = "###"; // Please set your Spreadsheet ID.
var sheetIds = [12345, 67890]; // Please set the sheet IDs.
// 1. Create new Spreadsheet as a temporal.
var temp = SpreadsheetApp.create("temp");
var tempId = temp.getId();
// 2. Copy the selected sheets to the temp Spreadsheet.
SpreadsheetApp.openById(ssID).getSheets().filter(s => sheetIds.includes(s.getSheetId())).forEach(s => s.copyTo(temp).setName(s.getSheetName()));
temp.deleteSheet(temp.getSheets()[0]);
// 3. Export the temp Spreadsheet as a XLSX file.
var url = "https://docs.google.com/spreadsheets/d/" + tempId + "/export?format=xlsx";
var params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
var response = UrlFetchApp.fetch(url, params);
DriveApp.createFile(response).setName(name);
// 4. Remove the temp Spreadsheet.
DriveApp.getFileById(tempId).setTrashed(true);
}
References:
filter()
forEach()
copyTo(spreadsheet) of Class Sheet

Trying export email to sendgrid account using google apps script from google sheet)?

I'm trying export email from google sheet to my Sendgrid account:
function myFunction() {
var API_KEY = "your api key";
var url = "https://api.sendgrid.com/v3/contactdb/recipients=" + API_KEY;
var response = UrlFetchApp.fetch(url);
var data = JSON.parse(response.getContentText());
var results = data.hits;
var sheet = SpreadsheetApp.getActiveSheet();
var header = ["Email"]
var items = [header];
results.forEach(function (result) {
items.push([result.email]);
});
sheet.getRange(1,1,items.length,items[0].length).setValues(items);
}
To finish that script I'm only need to insert my Sendgrid API key, but it still not working...
Maybe I choosen wrong "var url =" link?
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#Add-Single-Recipient-POST

Cannot extract and import CSV from ZIP in website to Google Sheets (App Scripts) with Basic Auth

I'm trying to get a CSV that is zipped in a URL, which needs basic auth. I can't get to do it. I get a syntax error on 'files' argument. This is what I tried:
function importdatastreamcsv() {
var user = 'user';
var pw = 'pass';
var csvUrl = 'https://example.com/api/datastream/download/58350?tableIds=67595&usePreferences=false';
var csvContent = UrlFetchApp.fetch(csvUrl,{headers: {'Authorization': 'Basic ' + Utilities.base64Encode(user + ':' + pw, Utilities.Charset.UTF_8)}});
var files = Utilities.unzip(csvContent)[0]; //syntax error on the argument! :(
var csvData = Utilities.parseCsv(files.getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet().getActiveCell();
sheet.setValues(csvData);
}
Looking for other alternatives, I noticed that is possible to pull the data in html table (not zip-csv format), so I wrote another script. It kind of worked, but all the information is in plain html and stored in only one cell, so it's almost impossible to read... here is the code:
function importdatastreamhtml() {
var user = 'user';
var pw = 'pass';
var csvUrl = 'https://example.com/api/datastream/download/58350?tableIds=67595&usePreferences=false&format=web';
var csvContent = UrlFetchApp.fetch(csvUrl,{headers: {'Authorization': 'Basic ' + Utilities.base64Encode(user + ':' + pw, Utilities.Charset.UTF_8)}});
var html = csvContent.getContentText();
var sheet = SpreadsheetApp.getActiveSheet().getRange(1, 1);
sheet.setValue(html);
}
I need to have at least one of these two running correctly. What can I be missing here?
The output should be a simple table.
Many thanks,
César

Google script xls attachment not displaying

any thoughts as to why this script emails an attachment but the attachment is not the correct spreadsheet, and looks like some sort of google error page.
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
Logger.log(url);
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(ss.getName() + ".xlsx");
MailApp.sendEmail("youremail#email.com", "Google Sheet to Excel", "The XLSX file is attached", {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
}
I guess API has changed. You can try Drive REST API(v3) instead. Replace
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + ss.getId() + "&exportFormat=xlsx";
var params = { ... };
var blob = UrlFetchApp.fetch(url, params).getBlob();
to
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() +
"/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" +
"{your API key}";
var blob = UrlFetchApp.fetch(url).getBlob();
I tested and it worked. Of course you first should get your own API key, etc, at API Manager. Then you can try some APIs like simple GET requests at APIs Explorer. Or you can try some APIs, in this case Files: export, also at the documentation page itself, but notice that you cannot try your own API key here.
This is the updated code that #sangbok helped with:
function getGoogleSpreadsheetAsExcel(){
try {
var ss = SpreadsheetApp.getActive();
var sheet = DriveApp.getFileById(ss.getId());
// sets sharing to public - to send out email.
sheet.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT);
var url = "https://www.googleapis.com/drive/v3/files/" + ss.getId() + "/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&key=" + "YOURAPIKEYGOESHERE4";
var blob = UrlFetchApp.fetch(url).getBlob();
Logger.log(url);
blob.setName(ss.getName() + ".xlsx");
var now = new Date();
MailApp.sendEmail("YOUREMAILADDRESSGOESHERE", "EMAIL SUBJECT " + now , "EMAIL BODY " + now , {attachments: [blob]});
} catch (f) {
Logger.log(f.toString());
}
// returns the file back to Private access
sheet.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.EDIT);
}

Google Apps Script UrlFetchApp Exception

Im in the process of creating a custom timesheet using Google Docs and Google Apps Script. One of the requirements is to save the timsheet as a PDF when the user submits the timesheet. Heres what I currently have:
function createPdf(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+ ss.getId() + "&gid=0&portrait=true" +"&exportFormat=pdf";
var requestData = {
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(url, requestData);
var content = result.getBlob();
var file = DocsList.createFile(content);
return file;
}
When debugging the script, I get the following error:
Unexpected exception upon serializing continuation
Any help would be appreciated.
After some further digging, I found this solution:
function createPdf(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var pdf = ss.getAs("application/pdf");
var file = DocsList.createFile(pdf);
file.rename("Test");
return file;
}

Categories