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
Related
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
I need a script that creates a PDF with only one sheet of my spreadsheet.
I currently have a script that generates a PDF but does it with the entire file.
I can not copy the values to another file, since the sheet I need to export is graphics with data extracted from another sheet.
Could you help me? Thank you.
function myFunction() {
var archivo = SpreadsheetApp.getActive();
var hoja = archivo.getSheetByName("Graficos 2");
var id = archivo.getId();
var archivoId = DriveApp.getFileById(id);
var archivoBlob = archivoId.getBlob();
var carpetaId = archivoId.getParents();
var contenidoPDF = archivo.getAs(MimeType.PDF);
carpetaId.next().createFile(contenidoPDF);
}
This question has been addressed more or less here.
In short, you can modify export parameters in Url queryString to get a specific sheet. And then convert the blob to a pdf.
Here is the code for the same, base code was obtained from here
function emailSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "Your Email Id";
// Get the currently active spreadsheet URL (link)
// Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("<Your Sheet name>")
// Subject of email message
var subject = "PDF generated from sheet " + sheet.getName();
// Email Body can be HTML too with your logo image - see ctrlq.org/html-mail
var body = "Install the <a href='http://www.labnol.org/email-sheet'>Email Spreadsheet add-on</a> for one-click conversion.";
// Base URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());
/* Specify PDF export parameters
From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
*/
var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=letter' // paper size legal / letter / A4
+ '&portrait=false' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to page width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid='; // the sheet's Id
var token = ScriptApp.getOAuthToken();
//make an empty array to hold your fetched blobs
var blobs;
// Convert your specific sheet to blob
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
//convert the response to a blob and store in our array
blobs = response.getBlob().setName(sheet.getName() + '.pdf');
// Define the scope
Logger.log("Storage Space used: " + DriveApp.getStorageUsed());
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments:[blobs]
});
}
Edit: To combine specific sheets and convert it into and pdf.
Firstly you will have to obtain the sheet object of all the sheets you want to merge into the pdf
var sheet2 = ss.getSheetByName("<Your Sheet name>")
var sheet3 = ss.getSheetByName("<Your Sheet name>")
Then pass the sheetId of each of the sheet to the URL query delimited by %EE%B8%80, Like so
url += url_ext + sheet.getSheetId()+ "%EE%B8%80"+sheet2.getSheetId()+ "%EE%B8%80"+sheet3.getSheetId()
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
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
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);
}
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;
}