I have a Google Sheets spreadsheet with a simple button that I've created via Insert>Drawing. I would like to assign a script to the button that when clicked will download a different tab/sheet as an excel file to the local computer.
I already found this post with a solution that achieves the same result that I'm looking for, but it does it via a modal dialog/UI object. It uses the HTML service.
*Edit: Here is the code found in the post linked to above:
/**
* Adds a custom menu
*
* @param {Object} e The event parameter for a simple onOpen trigger.
*/
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Custom')
.addItem('Download as XLSX', 'downloadXLS_GUI')
.addToUi();
}
/**
* Display a modal dialog with a single download link.
*
* From: http://stackoverflow.com/a/37336778/1677912
*/
function downloadXLS_GUI() {
// Get current spreadsheet's ID, place in download URL
var ssID = SpreadsheetApp.getActive().getId();
var URL = 'https://docs.google.com/spreadsheets/d/'+ssID+'/export?format=xlsx';
// Display a modal dialog box with download link.
var htmlOutput = HtmlService
.createHtmlOutput('<a href="'+URL+'">Click to download</a>')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(80)
.setHeight(60);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Download XLS');
}
I have tried this solution and it does work, but I would like to know if this can be done with a simple button drawing instead; I.e., I want to assign the trigger to a shape that I can place on the sheet body itself instead of a custom menu added to the ribbon.
Any help would be much appreciated.
*Update: The idea above was to eliminate the need for the user to click a second time. After doing some more research it appears this is not possible unless the user changes their browser settings to allow popups. This is because by default, only a direct user action can open a URL. But my desired functionality would need to execute code which then would try to open the URL, so it is blocked by the browser. See more information here. So it seems this dialog box method is the best solution currently available.