Google Apps Script UrlFetchApp Exception - javascript

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

Related

Google Sheets Apps Script 'Unknown Function'

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.

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

Not able to load the response

var soapre1 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:glob=\"http://sap.com/xi/SAPGlobal20/Global\">";
var soapre2 = "<soapenv:Header/><soapenv:Body><glob:EmployeeLeaveRequestByParticipantQuery><EmployeeLeaveRequestSelectionByParticipant><EmployeeLeaveRequestParticipantRoleCode listVersionID=\"?\">2</EmployeeLeaveRequestParticipantRoleCode>";
var soapre3 = "<!--Zero or more repetitions:--> <EmployeeLeaveRequestParticipantWorkAgreementIDInterval><IntervalBoundaryTypeCode>1</IntervalBoundaryTypeCode> <!--Optional:--> <LowerBoundaryWorkAgreementID schemeID=\"?\" schemeAgencyID=\"?\">1009</LowerBoundaryWorkAgreementID></EmployeeLeaveRequestParticipantWorkAgreementIDInterval>";
var soapre4 = " <!--Zero or more repetitions:--> </EmployeeLeaveRequestSelectionByParticipant></glob:EmployeeLeaveRequestByParticipantQuery> </soapenv:Body></soapenv:Envelope>";
var soapRequest = soapre1+soapre2+soapre3+soapre4;
var authstr = 'Basic ' +Titanium.Utils.base64encode('S0009231839'+':'+ 'm8390967743!');
var soapxhr = Ti.Network.createHTTPClient();
soapxhr.setRequestHeader('SOAPAction',soapRequest);
soapxhr.open("POST","http://erp.esworkplace.sap.com/sap/bc/srt/pm/sap/ecc_empleavereqparctqr/800/default_profile/2/binding_t_http_a_http_ecc_empleavereqparctqr_default_profile");
soapxhr.setRequestHeader('Authorization', authstr);
soapxhr.setRequestHeader('Content-Type','text/xml','charset=utf-8');
soapxhr.send();
soapxhr.onload = function(e)
{
Ti.API.info('abcd');
//get the xml data and let it roll!
var doc = this.responseXML;
Ti.API.info(doc);
}
soapxhr.onerror = function (e){
alert('Error');
Ti.API.info(e);
}
Unable to load the response Its directly getting error
[INFO] {
source = "[object TiNetworkClient]";
type = error;
}
Any one advice how to fix the issue!
# Thanks in advance
In all browser its saying error! but i found some wsdl and soap request so in order to open the response i need to pass the method name to the http request ! then it working

Categories