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);
}
Related
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
I'm working with ARIS tool and I want to make calls(GET, POST...) in ARIS to ARIS API repository!
I have authentication that works when I try it directly in the repository, but I got an error when I debug the code I have in ARIS.
The error: Error running script: Connection refused: connect.
I have the following code:
var obj = new java.net.URL(url);
var con = obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", java.net.USER_AGENT);
var tenant = "";
var name = "";
var password = "";
var key = "";
var authString = tenant + ":" + name + ":" + password + ":" + key;
var encoder = new java.lang.String(Base64.encode(authString));
con.setRequestProperty("Authorization", "Basic" + encoder);
var responseCode = con.getResponseCode();
var iN = new java.io.BufferedReader(new java.io.InputStreamReader(con.getInputStream()));
var inputLine = new java.lang.String();
var response = new java.lang.StringBuffer();
while((inputLine = iN.readLine()) != null){
response.append(inputLine);
}
iN.close();
return new java.lang.String(response);
Is the problem that I use Basic authentication, but I have tenant and key also or it's something else?
Also, name, password, key and tenant I'm leaving empty for security purposes, but in the original code the values are inserted. Also the url parameter contains the url link that is called directly in the repository.
Can someone please help me?
Thanks!
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
im currently trying to call on a API using "GET" method in javascipt, but i don't seem to get any access. This is the code.
loadLibrary("cus:json3.js");
try {
var buffer = new MemoryBuffer();
buffer.fromString("username" + ':' + "password", "utf-8");
var http = new HttpClientRequest();
http.header["Authorization"] = "Basic " + buffer.toBase64();
this.baseURL = "https://url...";
http.url = this.baseURL;
http.method = "GET";
http.execute();
logInfo();
var response = http.response;
}
} catch(e) {
logInfo(e);
}
But all i get is -55 error. Not sure why I can't access the API like this. Does anybody have an idea that would be awsome. The firewall has allowed the IP that my program is using.
I'm trying to run a simple HTTP request with the following script :
function myFunction() {
var USERNAME = PropertiesService.getScriptProperties().getProperty('XXXXXX');
var PASSWORD = PropertiesService.getScriptProperties().getProperty('XXXXXXX');
var url = PropertiesService.getScriptProperties().getProperty('https://myurlapi');
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD)
};
var params = {
"method":"GET",
"headers":headers,
};
var response = UrlFetchApp.fetch(url, params);
}
When running the script I have the following error Attribute provided with no value: url (line 16, file "Code")
Line 16 is var response = UrlFetchApp.fetch(url, params);
I've positively tested the API with https://www.hurl.it/ and It's working. so what's wrong with my script ?
Ok, It's working with the following script :
function myFunction() {
var USERNAME = 'XXXXXXX';
var PASSWORD = 'XXXXXXX';
var url = 'myurlpi';
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(USERNAME + ':' + PASSWORD),
"Accept" : "*/*",
};
var params = {
"method":"GET",
"headers":headers,
"validateHttpsCertificates" :false
};
var response = UrlFetchApp.fetch(url, params);
Logger.log(response);
}
I basically get rid of of the PropertiesService.getScriptProperties().getProperty.
Would love to understand why ? :)