Export Google Sheet as .xlsx and send file to server - google-apps-script

My company manages non-confidential information in a Google Sheet. Every day, I export that sheet to .xlsx format and then upload it to various services for data syndication.
Normally, such a process could be automated using the "Publish to Web" feature. But for security reasons, that option is locked for all users.
I do have full permissions for Google Apps Script, though. So, I'd like to write a script for this. The particulars don't matter. Somehow, I need to export the sheet on a schedule and send it to an AWS server, where it can be automatically retrieved.
At the AWS side, I can easily set up an email server, FTP server, rclone, whatever. I just need to figure out what to do on the Google side first.
Can this be done?
What I have tried so far:
Export a Google Sheet to Google Drive in Excel format with Apps Script
function makeCopy() {
var formattedDate = Utilities.formatDate(new Date(), "CET", "yyyy-MM-dd' 'HH:mm");
var name = "Backup Copy " + formattedDate;
var destination = DriveApp.getFolderById("1vFL98cgKdMHLNLSc542pUt4FMRTthUvL");
// Added
var sheetId = "2SqIXLiic6-gjI2KwQ6OIgb-erbl3xqzohRgE06bfj2c";
var url = "https://docs.google.com/spreadsheets/d/" + sheetId + "/export?format=xlsx&access_token=" + ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url).getBlob().setName(name + ".xlsx"); // Modified
destination.createFile(blob);
}
--- OR ---
function convertSheetToXLSX() {
var sheetId = "2SqIXLiic6-gjI2KwQ6OIgb-erbl3xqzohRgE06bfj2c";
var spreadsheetName = "My Spreadsheet";
var destination = DriveApp.getFolderById("1vFL98cgKdMHLNLSc542pUt4FMRTthUvL");
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + sheetId + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
blob.setName(spreadsheetName + ".xlsx");
destination.createFile(blob);
}
I have tried these scripts from the URL posted above but it results in "An unknown error has occurred, please try again later."

Take a look at this thread. It is about sending a spreadsheet in PDF format, but if you just change the ExportOptions to xlsx, you should be able to make it.

Related

Revert Revision of an Excel File - Drive API

I have an Excel file on my Drive (web version). That Excel has many versions. I require the file every so often to revert to a specific version without deleting the most recent version.
I have the following code:
function revertRevisionExcel() {
var revisionId = "######"; // Revision ID to revert.
var fileId = "#####"; // Set the file ID.
var endpoint = "";
var token = ScriptApp.getOAuthToken();
Logger.log(token);
var res = Drive.Revisions.get(fileId, revisionId);
endpoint =
"https://www.googleapis.com/drive/v3/files/" +
fileId +
"/revisions/" +
revisionId +
"?pageToken=" +
token;
var mediaData = UrlFetchApp.fetch(endpoint).getBlob();
Drive.Files.update({}, fileId, mediaData);
}
When I run it shows me the error 401 "Login Required". Could any one please guide me?
Modification points:
About your question of When I run it shows me the error 401 "Login Required". Could any one please guide me?, when I saw your script, I think that the following modification is required.
token and res are not used.
I think that var token = ScriptApp.getOAuthToken() cannot be used for the query parameter of ?pageToken=" + token.
I think that the reason of your issue of Login Required is due to this. In this case, please use the access token retrieved by var token = ScriptApp.getOAuthToken() to the request header.
In order to retrieve the blob from the specific revision, please use alt=media in the query parameter.
When above modification points are reflected to your script, it becomes as follows.
Modified script:
function revertRevisionExcel() {
var revisionId = "######"; // Revision ID to revert.
var fileId = "#####"; // Set the file ID.
var endpoint = "https://www.googleapis.com/drive/v3/files/" + fileId + "/revisions/" + revisionId + "?alt=media";
var token = ScriptApp.getOAuthToken();
var mediaData = UrlFetchApp.fetch(endpoint, {headers: {authorization: "Bearer " + token}}).getBlob();
Drive.Files.update({}, fileId, mediaData);
}
Note:
In this modified script, it supposes that you have already enabled Drive API at Advanced Google services and the values of revisionId and fileId are the valid values. Please be careful this.
References:
Revisions: get
fetch(url, params)

How to get the “shareable link” of a Google Drive file via Google Apps Script and paste the link into a cell in Google Sheets?

I have a script that makes a PDF of my invoice and sends it to a Google drive folder.Now I want to get the "Shareable link" from the file it just made and paste it into a specific Cell in google Sheets. I don't have a coding background and at most I can understand and modify some code. So I'm using code I found online to create the PDF. I tried making my own code for the shareable link but I'm getting nowhere. Can anyone help me. This is the code I'm using for the PDF. If I can provide any more useful information please let me know. Thank you! :)
// Get the currently active spreadsheet URL (link)
var ss = SpreadsheetApp.getActiveSpreadsheet();
var token = ScriptApp.getOAuthToken();
var sheet = ss.getSheetByName("Invoice");
//Creating an exportable URL
var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());
var folderID = "#### Folder ID ####"; // Folder id to save in a folder.
var folder = DriveApp.getFolderById(folderID);
var invoiceNumber = ss.getRange("'Invoice'!I16").getValue()
var InvoiceDate = ss.getRange("!I17").getValue()
var pdfName = "Invoice #"+ invoiceNumber + " - " + Utilities.formatDate(new Date(), "GMT-7", "MM-dd-yyyy");
/* 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=true' // 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
// Convert individual worksheet to PDF
var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
//convert the response to a blob
var blobs = response.getBlob().setName(pdfName + '.pdf');
//saves the file to the specified folder of Google Drive
var newFile = folder.createFile(blobs);
// Define the scope
Logger.log("Storage Space used: " + DriveApp.getStorageUsed());
}```
Intuitively, you can achieve a lot only by yourself, and this is the way to go at the beginning:
You want to retrieve the link of the pdf, so you know for sure that it can happen only when the pdf has been created, which is after this line var newFile = folder.createFile(blobs);
Therefore newFile is the PDF you've created, what's left is just to get the link of this file, you can use either getUrl() or getId():
var newFileLink = newFile.getUrl()
or
var newFileLink = "http://drive.google.com/uc?export=view&id=" + newFile.getId()
Now you have stored the link of the created PDF, and you want to write data into your spreadsheet within a specific cell, maybe you want it in J16, since you're using invoiceNumber = ss.getRange("'Invoice'!I16").getValue() to get a value from I16
Assuming you want to set a value in J16. Intuitively again, since getValue retrieve something, so maybe something link setValue will do the opposite:
var writePDFLink = ss.getRange("'Invoice'!J16").setValue(newFileLink)
Hope this was insightful.

Output google sheet via email

I'm trying to output my custom google sheet to a set email address
I have tried adding into a blob before sending but every time the email is sent the excel sheet that is attached is blank. Any help would be appreciated
var file = DriveApp.getFilesByName(nSheet.getName());
var url = 'https://docs.google.com/spreadsheets/d/'+nSheet.getId()+'/export?format=xlsx';
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var fileName = (nSheet.getName()) + '.xlsx';
var blobs = [response.getBlob().setName(fileName)];
var emailAddress = "testg#gmail.com"
var subject = "PCS v5 Validated Sheet"
var emailbody = "The XLSX file is attached"
GmailApp.sendEmail(emailAddress, subject, emailbody, {attachments: blobs});
You script works fine. I tried it for simple sheet and I'm getting nice xlsx on my email.
https://docs.google.com/spreadsheets/d/1p8NzX0J1XhHFq6C1iSNWbs7h3OXzHKC7cDiQGYmuD_0/edit#gid=0
So, if your is blank it might be related to what data you have in sheet.
Are you using some =QUERY of =IMPORTXML function to get data which isn't diplayed?

Add a button to automatically download a google sheet to excel from a google application script

I have an application made on google than handdle different sheets on a google workbook. I need to add a button to allow users download some of these sheets but in an excel format if is possible. I took one code from StackOv and try to modify it, as i don´t want it name the file and save it in drive, i only need it download as same that when from excel it is download in Book1 ("libro1") without saving anywhere. THK!
var ss = SpreadsheetApp.openById("fffffffffffffffffffffffffffff...myID");
var sheetId = ss.ss.getSheetByName('nameSheetNeedToDownload');
var url = "https://docs.google.com/spreadsheets/d/" + sheetId + "/export?format=xlsx&access_token=" + ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url).getBlob().setName(name + ".xlsx");
createFile(blob); // here need to create but without saving
THK you Tanaike!...Yes here i copy the code i have
function downloadAsXlsx() {
var bogus = DriveApp.getRootFolder();
var spreadSheet = SpreadsheetApp.openById('WorkbookID');
var ssID = spreadSheet.getSheetByName('SheetName');
Logger.log(ssID);
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?format=xlsx";
var params = {method:"GET", headers:{"authorization":"Bearer "+
ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url, params);
// save to drive
DriveApp.createFile(response);
}

Converting spreadsheet into microsoft excel using Google Apps, but not working

Used below code to convert spreadsheet into xlsx.
Though looks to be working fine, But doesn't works same as Microsoft Excel. Looking help on alternative to convert spreadsheet into microsoft xlsx file or Blob.
Objective:
I have an API that accepts only Microsoft .xlsx with data available in Google Spreadsheet; and hence trying to convert spreadsheet into Microsoft xlsx.
My Code:
function exportToXlsx(){
var fileId = "{{fileID_of_spreadsheet}}";
var targetFolderID = "{{target_folderID}}";
Logger.log("Input File ID: " + fileId);
try {
var url = "https://docs.google.com/feeds/download/spreadsheets/Export?key=" + fileId + "&exportFormat=xlsx";
var params = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var blob = UrlFetchApp.fetch(url, params).getBlob();
//set name to blob
blob.setName(DriveApp.getFileById(fileId).getName() + ".xlsx");
//create the xlsx file
var newFile = DriveApp.createFile(blob);
} catch (f) {
Logger.log(f.toString());
}
}