I am working with Google Scripts Editor. The purpose of my script is to backup a spreadsheet from Google Sheets to my local as a csv. I would like each new backup to overwrite the previous backup file. Currently the script results in subsequent backup files as the same name but as a copy (Ex. filename (1).csv and filename (2).csv) Any help in overwriting would be appreciated.
function myFunction() {// UPDATE THE FOLDER ID for e.g. "My Drive > Docs > Backups"
var backupFolder = DriveApp.getFolderById("foldername");
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var spreadsheetId = spreadsheet.getId();
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks[MimeType.CSV];
// UPDATE THE SHEET-NAME TO BE EXPORTED - e.g. sheetName = "Malawi Ops"
// -- LEAVE IT BLANK TO EXPORT THE ENTIRE SPREADSHEET - i.e. sheetName = ""
var sheetName = "";
if (sheetName.length) {
var sheet = spreadsheet.getSheetByName(sheetName);
var sheetId = sheet.getSheetId();
url += "&gid=" + sheetId;
}
var token = ScriptApp.getOAuthToken();
var options = { headers: { Authorization: "Bearer " + token } };
var response = UrlFetchApp.fetch(url, options);
var doc = response.getBlob();
var backupDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd' 'HH-mm-ss");
var backupName = spreadsheet.getName() + ".csv";
var tempFile = DriveApp.createFile(doc).setName(backupName);
tempFile.makeCopy(backupName, backupFolder);
tempFile.setTrashed(true);
}
I understood that you are using your code to make CSV backups of your Sheets, and you want each new backup to override the old one. If I understood it well, you are very close from reaching your goal.
After copying the new backup, you only need to delete the old one. This isn't directly overwriting, but has the same result. Immediately after you created your new CSV, you can search for the old one and use File.isTrashed() on it. Please, don't hesitate to ask me any doubts.
Related
Hi Facing error while running code of Coverting excel to csv. Please guide what to edit to solve the query.
function makeCSV() {
var SourceFolder = DriveApp.getFolderById("1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN")
var DestinationFolder = DriveApp.getFolderById("1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj")
var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" +
MimeType.MICROSOFT_EXCEL_LEGACY + "'";
var sourceFiles = SourceFolder.searchFiles(searchQuery);
var now = new Date();
var properties = PropertiesService.getScriptProperties();
var cutoff_datetime = properties.getProperty('last_execution_time');
if(cutoff_datetime)
cutoff_datetime = new Date(cutoff_datetime);
while (sourceFiles.hasNext()){
var sourceFile = sourceFiles.next();
if(!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime){
var fileId = sourceFile.getId();
var Spreadsheet = Drive.Files.copy({mimeType: MimeType.csv, parents:
[{id:"1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj"}]}, fileId);
}
}
properties.setProperty('last_execution_time',now.toString());
}
Unfortunately, XLSX data cannot be directly converted to CSV data using Google Apps Script. And, Drive.Files.copy can convert non-Google Docs files to Google Docs files. Please be careful about this. I think that this is the reason for your current issue. In order to convert XLSX data to CSV data using Google Apps Script, it is required to do the following flow.
Convert XLSX data to Google Spreadsheet.
Convert Google Spreadsheet to CSV data.
Remove Google Spreadsheet.
When this flow is reflected in your script, it becomes as follows.
Modified script:
function makeCSV() {
var SourceFolder = DriveApp.getFolderById("1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN");
var DestinationFolder = DriveApp.getFolderById("1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj");
var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" + MimeType.MICROSOFT_EXCEL_LEGACY + "'";
var sourceFiles = SourceFolder.searchFiles(searchQuery);
var now = new Date();
var properties = PropertiesService.getScriptProperties();
var cutoff_datetime = properties.getProperty('last_execution_time');
if (cutoff_datetime) cutoff_datetime = new Date(cutoff_datetime);
var token = ScriptApp.getOAuthToken();
while (sourceFiles.hasNext()) {
var sourceFile = sourceFiles.next();
if (!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime) {
var fileId = sourceFile.getId();
var ssId = Drive.Files.copy({mimeType: MimeType.GOOGLE_SHEETS, parents: [{ id: "1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj" }]}, fileId).id;
var url = "https://docs.google.com/spreadsheets/export?exportFormat=csv&id=" + ssId;
var blob = UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + token}}).getBlob();
DestinationFolder.createFile(blob.setName(sourceFile.getName().split(".")[0] + ".csv"));
DriveApp.getFileById(ssId).setTrashed(true);
}
}
properties.setProperty('last_execution_time', now.toString());
}
When this script is run, the XLSX data is converted to Google Spreadsheet, and Google Spreadsheet is converted to CSV data. The CSV file is created to DestinationFolder folder.
Note:
This script used Drive API. So, please enable Drive API at Advanced Google services.
References:
Files: copy
fetch(url, params)
I have a Google Form that does two things upon hitting the Submit button. First, it dumps that data into a Spreadsheet, then it autofills a Google Doc Template with the info from the Form.
In my script to autofill the Google Doc, I've grabbed the URL for the Google Doc. But I need to write this URL into the last row of Column J in my Google Sheet. Correction: using the getActiveSheet functions are fine, I forgot this script is running from the (Active) Google Sheet (apologies!).
Can anyone assist with this? Here's a snippet of the script to get the URL:
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var TimeStamp = e.values[0];
var Technician = e.values[1];
var Vendor = e.values[2];
var xxx = e.values[3];
var yyy = e.values[4];
var SerialNumber = e.values[5];
var AssetTag = e.values[6];
var TicketNumber = e.values[7];
var HostName = e.values[8];
var DocumentLink = e.values[9];
var Return = e.values[10];
var Platform = e.values[11];
var Summary = e.values[12];
var URL = "";
//file is the template file, and you get it by ID
var file = DriveApp.getFileById('aaa');
//Put auto filled Google Doc into the appropriate Vendor Folder
//file.makeCopy will return a Google Drive file object
if (Vendor == "111") {
var folder = DriveApp.getFolderById('bbb')
var copy = file.makeCopy(TicketNumber + ' - ' + SerialNumber, folder);
}
if (Vendor == "222") {
var folder = DriveApp.getFolderById('ccc')
var copy = file.makeCopy(TicketNumber + ' - ' + SerialNumber, folder);
}
if (Vendor == "333") {
var folder = DriveApp.getFolderById('ddd')
var copy = file.makeCopy(TicketNumber + ' - ' + SerialNumber, folder);
}
//Once we've got the new file created, we need to open it as a document by using its ID
var doc = DocumentApp.openById(copy.getId());
//Get the url of the newly created Google Doc
var url = doc.getUrl();
//Script to write this URL into the Shared Google Sheet will go here
//Since everything we need to change is in the body, we need to get that
var body = doc.getBody();
//Then we call all of our replaceText methods
body.replaceText('{{EmailAddress}}', Technician);
body.replaceText('{{TicketNumber}}', TicketNumber);
body.replaceText('{{HostName}}', HostName);
body.replaceText('{{SerialNumber}}', SerialNumber);
body.replaceText('{{AssetTag}}', AssetTag);
body.replaceText('{{Summary}}', Summary);
body.replaceText('{{Vendor}}', Vendor);
body.replaceText('{{URL}}', url);
//Lastly we save and close the document to persist our changes
doc.saveAndClose();
Thanks in advance!
From your following situation in your question,
Also this is a shared Google Sheet, so I can't use the getActiveSheet function, I'd need to reference the Google Sheet URL, I believe.
If you have the permission to write the values to the shared Google Spreadsheet, how about the following modification?
From:
var url = doc.getUrl();
//Script to write this URL into the Shared Google Sheet will go here
To:
var url = doc.getUrl();
//Script to write this URL into the Shared Google Sheet will go here
var sheet = SpreadsheetApp.openById("### Spreadsheet ID ###").getSheetByName("### sheet name ###");
sheet.appendRow([url]);
In this modification, please set the Spredsheet ID and sheet name. By this, the value of url is appended to the next row of the last row of the sheet in the Google Spreadsheet.
If you want to use the Spreadsheet URL instead of Spreadsheet ID, please modify openById("### Spreadsheet ID ###") to openByUrl("### Spreadsheet URL ###").
References:
openById(id)
openByUrl(url)
appendRow(rowContents)
Edit:
From the following replying,
That doesn't seem to work to insert the URL into the last row of column J unfortunately. It looks like this script can use the Active Sheet afterall, I'll edit the OP.
In this case, how about the following modification?
From:
var url = doc.getUrl();
//Script to write this URL into the Shared Google Sheet will go here
To:
var url = doc.getUrl();
//Script to write this URL into the Shared Google Sheet will go here
// var sheet = SpreadsheetApp.openById("### Spreadsheet ID ###").getSheetByName("### sheet name ###");
var sheet = SpreadsheetApp.getActiveSheet(); // or SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheetname")
sheet.getRange("J" + (sheet.getLastRow() + 1)).setValue(url);
Or
var url = doc.getUrl();
//Script to write this URL into the Shared Google Sheet will go here
// This is from https://stackoverflow.com/a/44563639/7108653
Object.prototype.get1stEmptyRowFromTop = function (columnNumber, offsetRow = 1) {
const range = this.getRange(offsetRow, columnNumber, 2);
const values = range.getDisplayValues();
if (values[0][0] && values[1][0]) {
return range.getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow() + 1;
} else if (values[0][0] && !values[1][0]) {
return offsetRow + 1;
}
return offsetRow;
};
// var sheet = SpreadsheetApp.openById("### Spreadsheet ID ###").getSheetByName("### sheet name ###");
var sheet = SpreadsheetApp.getActiveSheet(); // or SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheetname")
sheet.getRange("J" + sheet.get1stEmptyRowFromTop(10)).setValue(url);
Suggestion:
If you need to write the URL value into the last row of Column J in a shared Google Spreadsheet file, you can try this sample below:
function sample() {
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/SHEET_ID_IS_HERE/edit#gid=0');
var sheet = ss.getSheets()[0]; // access first sheet
var activeSheet = ss.setActiveSheet(sheet);
//Sample setValue() action to the shared sheet file
activeSheet.getRange("A1").setValue("URL");
}
NOTE: You would need to have an editor permission on the Shared Google Sheet file that you're accessing
References:
openByUrl(url)
getSheets()
setActiveSheet(sheet)
Here's the code that ended up working for me.
//Get the url of the newly created Google Doc
var url = doc.getUrl();
// var sheet = SpreadsheetApp.openById("### Spreadsheet ID ###").getSheetByName("### sheet name ###");
var sheet = SpreadsheetApp.getActiveSheet(); // or SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheetname")
sheet.getRange("J" + (sheet.getLastRow())).setValue(url);
I have been trying to combine two scripts to create a script that i can run on demand by using a custom menu. I would like the script to do the following:
Make a copy with values and format only (no formulas and importrange), of a existing spreadsheet.
Name the copy the same as the original spreadsheet + timestamp in "yyyy-mm-dd" format.
Place the copy in a specific subfolder.
Also to be able to create the copy on demand, using a custom menu button to do so.
And lastly to have a custom menu button for easy access to said subfolder.
So far i have found two scripts that can do parts of this task but have not been able to combine them to a single script. Is this possible?
See the code below for the two scripts:
SCRIPT 1
// Program: Archive GSheet with Date Stamp
// Programmer: Michael Fryar
// Date: 19 September 2017
// Google Apps Script to copy Google Sheet to subfolder with date stamp in name
// Add Custom Menu
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Archive')
.addItem('Archive a copy with timestamp', 'archiveCopy')
.addItem('Open folder', 'openArchive')
.addToUi();
}
// Define function to copy sheet to subfolder with date stamp in name
// Building on https://gist.github.com/abhijeetchopra/99a11fb6016a70287112
function archiveCopy() {
// Replace "spreadsheetId" with the ID of the Google Sheet you wish to copy
var file = DriveApp.getFileById("ID")
// Replace "folderId" with the ID of the folder where you want the copy saved
var destination = DriveApp.getFolderById("ID");
// Get timezone for datestamp
var timeZone = Session.getScriptTimeZone();
// Generate datestamp and store in variable formattedDate as year-month-date
var formattedDate = Utilities.formatDate(new Date(), timeZone , "yyyy-MM-dd");
// Replace "file_name" with the name you want to give the copy
var name = formattedDate + " Copy";
// Archive copy of "file" with "name" at the "destination"
file.makeCopy(name, destination);
}
// Define function to open archive folder in new tab
// Building on https://www.youtube.com/watch?v=2y7Y5hwmPc4
function openArchive() {
// Replace "folderId" with the ID of the folder where you want copies saved
var url = "https://drive.google.com/drive/folders/"
// HTML to open folder url in new tab and then close dialogue window in sheet
var html = "<script>window.open('" + url + "');google.script.host.close();</script>";
// Push HTML into user interface
var userInterface = HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModalDialog(userInterface, 'Opening Archive Folder');
}
SCRIPT 2
function copyEntireSpreadsheet() {
var id = "ID"; // Please set the source Spreadsheet ID.
var ss = SpreadsheetApp.openById(id);
var srcSheets = ss.getSheets();
var tempSheets = srcSheets.map(function(sheet, i) {
var sheetName = sheet.getSheetName();
var dstSheet = sheet.copyTo(ss).setName(sheetName + "_temp");
var src = dstSheet.getDataRange();
src.copyTo(src, {contentsOnly: true});
return dstSheet;
});
var destination = ss.copy(ss.getName() + " - " + new Date().toLocaleString());
tempSheets.forEach(function(sheet) {ss.deleteSheet(sheet)});
var dstSheets = destination.getSheets();
dstSheets.forEach(function(sheet) {
var sheetName = sheet.getSheetName();
if (sheetName.indexOf("_temp") == -1) {
destination.deleteSheet(sheet);
} else {
sheet.setName(sheetName.slice(0, -5));
}
});
}
UPDATE!
I found another script that could do the parts that i needed and was finally able to combine them together. Posting script below to benefit others in search of something similar:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Archive')
.addItem('Archive copy with timestamp', 'Archive')
.addItem('Open folder', 'openArchive')
.addToUi();
}
function Archive() {
var spreadsheetId = "###"; // Please set the source Spreadsheet ID.
var destFolderId = "###"; // Please set the destination folder ID.
// Copy each sheet in the source Spreadsheet by removing the formulas as the temporal sheets.
var ss = SpreadsheetApp.openById(spreadsheetId);
var tempSheets = ss.getSheets().map(function(sheet) {
var dstSheet = sheet.copyTo(ss).setName(sheet.getSheetName() + "_temp");
var src = dstSheet.getDataRange();
src.copyTo(src, {contentsOnly: true});
return dstSheet;
});
// Get timezone for datestamp
var timeZone = Session.getScriptTimeZone();
// Generate datestamp and store in variable formattedDate as year-month-date
var formattedDate = Utilities.formatDate(new Date(), timeZone , "yyyy-MM-dd");
// Copy the source Spreadsheet.
var destination = ss.copy(ss.getName() + " " + formattedDate);
// Delete the temporal sheets in the source Spreadsheet.
tempSheets.forEach(function(sheet) {ss.deleteSheet(sheet)});
// Delete the original sheets from the copied Spreadsheet and rename the copied sheets.
destination.getSheets().forEach(function(sheet) {
var sheetName = sheet.getSheetName();
if (sheetName.indexOf("_temp") == -1) {
destination.deleteSheet(sheet);
} else {
sheet.setName(sheetName.slice(0, -5));
}
});
// Move file to the destination folder.
var file = DriveApp.getFileById(destination.getId());
DriveApp.getFolderById(destFolderId).addFile(file);
file.getParents().next().removeFile(file);
}
// Define function to open archive folder in new tab
// Building on https://www.youtube.com/watch?v=2y7Y5hwmPc4
function openArchive() {
// Replace "folderId" with the ID of the folder where you want copies saved
var url = "https://drive.google.com/drive/folders/folderid"
// HTML to open folder url in new tab and then close dialogue window in sheet
var html = "<script>window.open('" + url + "');google.script.host.close();</script>";
// Push HTML into user interface
var userInterface = HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModalDialog(userInterface, 'Opening Archive Folder');
}
This question already has an answer here:
Creating PDF in Landscape (Google Apps Script)
(1 answer)
Closed 3 months ago.
I have a code that, upon a submission from a linked form, will select the row with the most recently submitted information, which auto-fills another sheet in the format I prefer and then saves that as a PDF. I have used this code for several worksheets but now I have need of it on a sheet that contains an image. My PDF is saving without the image, which is essential to the process. In addition to this, I would also like it to save in landscape if someone could help with that, I'd appreciate it.
I've played around with the code a bit, but I had help with writing it and don't understand the language enough to make this work.
function generatePdf() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheeta = ss.getSheetByName('Firstsheet');
sheeta.getRange("A2:A").clear();
var lastrow = sheeta.getLastRow();
var range = sheeta.getRange(lastrow, 1);
var values = range.setValue("autofill"); //This is a checkbox in column A which triggers the vlookup on the second sheet
var originalSpreadsheet = SpreadsheetApp.getActive();
var sourcesheet = originalSpreadsheet.getSheetByName("Secondsheet");
var sourcerange = sourcesheet.getRange('A:I');
var sourcevalues = sourcerange.getValues();
var data = sourcesheet.getDataRange().getValues();
var pdfname = sourcesheet.getRange('E34').getDisplayValue();
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var projectname = SpreadsheetApp.getActiveSpreadsheet();
var sheet = sourcesheet.copyTo(newSpreadsheet);
var destrange = sheet.getRange('A:I');
destrange.setValues(sourcevalues);
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
var pdf = DriveApp.getFileById(newSpreadsheet.getId());
var theBlob = pdf.getBlob().getAs('application/pdf').setName("Sheet" + pdfname);
var folderID = "folder ID goes here";
var folder = DriveApp.getFolderById(folderID);
var newFile = folder.createFile(theBlob);
DriveApp.getFileById(newSpreadsheet.getId()).setTrashed(true);
sheeta.getRange("A2:A").clear();
}
I need the image in A1:F29 (merged) to save into the intermediary sheet that this formula creates to then save to the PDF. It would also be nice to save in landscape if at all possible.
1) The problem with the missing image is that you’re making the copy process twice, the first one using copyTo() function which copy the all sheet correctly. And then a second one where you use:
var destrange = sheet.getRange('A:I');
destrange.setValues(sourcevalues);
Which copy all the data, even “over the cell” images but not “in cell” images (probably because this is a new Sheets feature), which probably is the problem you’re facing. So you should delete those 2 lines of code in order to not override the first copy process. That’s what i did and worked fine.
2) As there is no option to specify the landscape feature, you can use the method they used in the link provided by #cooper [1] making a request to the export Url. I implemented the code and worked as intended, you just have to erase these 2 lines:
var pdf = DriveApp.getFileById(newSpreadsheet.getId());
var theBlob = pdf.getBlob().getAs('application/pdf').setName("Sheet" + pdfname);
For this:
var url = newSpreadsheet.getUrl();
//remove the trailing 'edit' from the url
url = url.replace(/edit$/, '');
//additional parameters for exporting the sheet as a pdf
var url_ext = 'export?exportFormat=pdf&format=pdf' + //export as pdf
//below parameters are optional...
'&portrait=false' + //orientation, false for landscape
'&gid=' + newSpreadsheet.getSheetId(); //the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName("Sheet" + pdfname);
[1] https://ctrlq.org/code/19869-email-google-spreadsheets-pdf
I've been reading up on how to save a spreadsheet to PDF via Google Docs Scripting. Most suggestions I've come across reference using something like:
theOutputFile.saveAndClose();
DocsList.createFile(theOutputFile.getAs('application/pdf')).rename(theOutputName+".pdf");
That is, they reference the saveAndClose() function. I don't want to save or close my spreadsheet - but I do want to download the current sheet as a PDF.
Any suggestions? Thanks.
For saving the current sheet as a PDF, you can hide all the other sheets, save the current, & then show all sheets again.
The pdf creation might start before the end of the sheets' hiding and then will include 2 sheets - the current & the last sheets - in the pdf file.
Adding a sleep or a confirmation msgbox, between showOneSheet & createPdf eliminated the problem.
This answer is a variation of Marco Zoqui's answer: "To send a single sheet you may hide all other before sending" in Google Apps Script to Email Active Spreadsheet
var sheet = SpreadsheetApp.getActiveSheet();
var sheetToSave = sheet.getName();
showOneSheet(sheetToSave);
Utilities.sleep(2000);
createPdf("TestFolder", "TestPDF");
showAllSheets();
function showOneSheet(SheetToShow) {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for(var i in sheets){
if (sheets[i].getName()==SheetToShow){
sheets[i].showSheet();
}
else {
sheets[i].hideSheet();
}
}
}
function showAllSheets() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for(var i in sheets){
sheets[i].showSheet();
}
}
function createPdf(saveToFolder, fileName){
var ssa = SpreadsheetApp.getActiveSpreadsheet();
var pdf = ssa.getAs("application/pdf");
try {
var folder = DocsList.getFolder(saveToFolder);
}
//Create Folder if not exists
catch(error){
folder = DocsList.createFolder(saveToFolder);
}
var file = folder.createFile(pdf);
file.rename(fileName);
return file;
}
I was able to get it to work using #hsgv's answer, however, this is the version I ended up using based on this.
// global save to folder variable:
var folderName = "My/Special/Folder";
function createInvoiceInGoogleDrive(){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
// getting some values from the spreadhseet for the file name
var invoiceNumber = sheet.getRange("E3").getValue();
var vendor = sheet.getRange("A9").getValue();
var fileName = invoiceNumber + ' - ' + vendor + " - Invoice.pdf";
var pdfBlob = sheetToPDF(spreadsheet, sheet);
pdfBlob.setName(fileName);
var folder = getOrCreateFolder(folderName);
var matchingFileList = folder.find(fileName);
if ( matchingFileList.length > 0 ) {
Browser.msgBox("ERROR: New invoice not created. " + fileName + " already exists at " + folderName);
return false;
} else {
var f = folder.createFile(pdfBlob);
spreadsheet.toast('Created a new invoice on Google Drive!');
return true;
}
}
// thanks: https://gist.github.com/gregorynicholas/9008572
function sheetToPDF(spreadsheet, sheet) {
var ssID = spreadsheet.getId();
var gid = sheet.getSheetId();
// &gid=x at the end of above url if you only want a particular sheet
var url2 = "http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ssID +
"&gid=" + gid +
"&fmcmd=12&size=7&fzr=true&portrait=true&fitw=true&locale=en&gridlines=false&printtitle=false&sheetnames=false&pagenum=UNDEFINED&attachment=true";
// AUTH TOKEN required to access the UrlFetchApp call below. You can receive it
// from https://appscripts.appspot.com/getAuthToken
var AUTH_TOKEN = "{GET YOUR OWN AUTH TOKEN}";
var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url2, {headers: {Authorization: auth}}).getBlob();
return res;
}
/**
* Get or create a folder based on its name/path
*/
function getOrCreateFolder(folderName) {
try {
var theFolder = DocsList.getFolder(folderName);
} catch(error){
var theFolder = DocsList.createFolder(folderName);
}
return theFolder;