Modifying a function to download a sheet - google-apps-script

I'm looking to modify this function so I don't actually need to click a Download Now link. I'd just like the script to download the sheet automatically. Appreciate any help. Thank you.
function copySheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("Road MT");
ss.rename(first.getRange(2, 14).getValue());
// this would change the name to whatever is in Row 2, col 14
var myValue =
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("N2")
.getValue();
var copiedSpreadSheet =
SpreadsheetApp.getActiveSpreadsheet().copy(myValue);
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('Download Now')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(300)
.setHeight(40);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Download XLS');
}

You can do that, but you need to invoke the download from doGet or doPost like this:
function doGet(fileId) {
var URL = 'https://docs.google.com/spreadsheets/d/'+fileId+'/export?format=xlsx';
var fileName = 'download.xlsx';
var blob = DriveApp.getFileById(fileId).getBlob();
return ContentService.createTextOutput(blob).downloadAsFile(fileName);
}

Related

google sheets UiApi to htmlservice script file upload

I got the problem since google isnt supporting UIapi anymore i cant use the code below. Could someone help me with it and re-edit to html service? I have no clue about any of those stuff. Code was copied from other site long time ago. Tryed to find a solution for the last 2 days and nothing. Would be really greatfull.
regards
// upload document into google spreadsheet
// and put link to it into current cell
function onOpen(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var menuEntries = [];
menuEntries.push({name: "", functionName: "doGet"});
ss.addMenu("", menuEntries);
}
function doGet(e) {
var app = UiApp.createApplication().setTitle("");
SpreadsheetApp.getActiveSpreadsheet().show(app);
var form = app.createFormPanel().setId('frm').setEncoding('multipart/form-data');
var formContent = app.createVerticalPanel();
form.add(formContent);
formContent.add(app.createFileUpload().setName('thefile'));
// these parameters need to be passed by form
// in doPost() these cannot be found out anymore
formContent.add(app.createHidden("activeCell", SpreadsheetApp.getActiveRange().getA1Notation()));
formContent.add(app.createHidden("activeSheet", SpreadsheetApp.getActiveSheet().getName()));
formContent.add(app.createHidden("activeSpreadsheet", SpreadsheetApp.getActiveSpreadsheet().getId()));
formContent.add(app.createSubmitButton(''));
app.add(form);
SpreadsheetApp.getActiveSpreadsheet().show(app);
return app;
}
function doPost(e) {
var app = UiApp.getActiveApplication();
app.createLabel('');
var fileBlob = e.parameter.thefile;
var doc = DriveApp.getFolderById('0BzI2pkyLXZ5maWo5b2Uyb3JWdzQ').createFile(fileBlob);
var label = app.createLabel('');
// write value into current cell
var value = 'hyperlink("' + doc.getUrl() + '";"' + doc.getName() + '")'
var activeSpreadsheet = e.parameter.activeSpreadsheet;
var activeSheet = e.parameter.activeSheet;
var activeCell = e.parameter.activeCell;
var label = app.createLabel('');
app.add(label);
SpreadsheetApp.openById(activeSpreadsheet).getSheetByName(activeSheet).getRange(activeCell).setFormula(value);
app.close();
return app;
}

Can not run standalone Google App Script from a Google Spreadsheet

I have a google spreadsheet shared with co-workers to keep track of task status. And I want to set a function through a menu to block some ranges in which the tasks were completed. The protective permissions are set to only allow me (owner) to edit it.
I've built a standalone script to run as me for this shared spreadsheet by using UrlFetch. I've tried many kinds of codes but it didn't work. The below are 3 versions I tried.
And, of course, I set "Who has access to the app: Anyone, even anonymous" in the standalone script.
Photo 1: Standalone script setting
Thanks so much!
1st version: Without using Content Service
//In standalone script
function doGet(e){
var taskRange = e.parameter.taskRange;
var ss = SpreadsheetApp.openById('SHARING_SPREADSHEET_ID');
var sh = ss.getSheetByName('Sheet1');
var protection = sh.getRange(taskRange).protect().setDescription('Completed Task')
var result = protection.removeEditors(protection.getEditors())
return result
}
//In sharing spreadsheet script
var url = "https://script.google.com/macros/s/STANDALONE_SCRIPT_ID/exec"
function onOpen(){
SpreadsheetApp.getUi().createMenu('TASK')
.addItem('Protect Task', 'protectTask')
.addToUi();
}
function protectTask(){
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange()
var response = UrlFetchApp.fetch(url+"?taskRange="+taskRange);
Logger.log(response);
}
2nd version: Using Content Service
//In standalone script
function doGet(e){
var taskRange = e.parameter.taskRange;
var ss = SpreadsheetApp.openById('SHARING_SPREADSHEET_ID');
var sh = ss.getSheetByName('Sheet1');
var protection = sh.getRange(taskRange).protect().setDescription('Completed Task')
var result = protection.removeEditors(protection.getEditors())
return ContentService.createTextOutput(result)
}
//In sharing spreadsheet script
var url = "https://script.google.com/macros/s/STANDALONE_SCRIPT_ID/exec"
function onOpen(){
SpreadsheetApp.getUi().createMenu('TASK')
.addItem('Protect Task', 'protectTask')
.addToUi();
}
function protectTask(){
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange()
var response = UrlFetchApp.fetch(url+"?taskRange="+taskRange).getContentText();
Logger.log(response);
}
3rd version: Using Content Service with JSON
//In standalone script
function doGet(e){
var taskRange = e.parameter.taskRange;
var ss = SpreadsheetApp.openById('SHARING_SPREADSHEET_ID');
var sh = ss.getSheetByName('Sheet1');
var protection = sh.getRange(taskRange).protect().setDescription('Completed Task')
var result = protection.removeEditors(protection.getEditors())
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON)
}
//In sharing spreadsheet script
var url = "https://script.google.com/macros/s/STANDALONE_SCRIPT_ID/exec"
function onOpen(){
SpreadsheetApp.getUi().createMenu('TASK')
.addItem('Protect Task', 'protectTask')
.addToUi();
}
function protectTask(){
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange()
var response = UrlFetchApp.fetch(url+"?taskRange="+taskRange).getContentText();
var result = JSON.Parse(response)
Logger.log(result);
}
One problem is this line:
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange()
Should be:
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange().getA1Notation();
Currently, the variable taskRange is a "class" It's not a string. You need to send a string.
FINALLY IT WORKS. I think the script was not running properly because I modified many times with many kinds of code. Therefore, I've created a new one and used the "stringified" log as #SandyGood suggested.
Many thanks to you all, specially, #SandyGood.
FINAL SCRIPTS
//In standalone script
function doGet(e){
var taskRange = e.parameter.taskRange;
var ss = SpreadsheetApp.openById('SHARING_SPREADSHEET_ID');
var sh = ss.getSheetByName('Sheet1');
var protection = sh.getRange(taskRange).protect().setDescription('Completed Task');
var result = protection.removeEditors(protection.getEditors());
var resultStr = JSON.stringify(result);
Logger.log('resultStr: ' + resultStr);
}
//In sharing spreadsheet script
var url = "https://script.google.com/macros/s/STANDALONE_SCRIPT_ID/exec"
function onOpen(){
SpreadsheetApp.getUi().createMenu('TASK')
.addItem('Protect Task', 'protectTask')
.addToUi();
}
function protectTask(){
var taskRange = SpreadsheetApp.getActiveSheet().getActiveRange().getA1Notation();
var response = UrlFetchApp.fetch(url+"?taskRange="+taskRange).getContentText();
Logger.log(response);
}

How to open link fetched from google spreadsheet to a html form button

I am able to fetch url from a google spreadsheet but don't know how to open it through html form button.
here is my code.js
function openInputDialog() {
var html =
HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add Item');
}
function getURL() {
var ss = SpreadsheetApp.getActiveSheet();
var range = ss.getRange("F2:F3");
Logger.log(range.getValue());
Logger.log(range.getFormulaR1C1());
var url = /"(.*?)"/.exec(range.getFormulaR1C1())[1];
}
here is my html button :-
<button onclick=" window.open('url','_blank')"> Open Website</button>
Thanks you in advance.
To fetch link from the hyperlink formula use the below code.
function fetchUrls(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1"); //Enter your sheet Name
var link = sheet.getRange("F2").getFormulaR1C1()
var url = /"(.*?)"/.exec(link)[1];
Logger.log(url)
return url;
}

How to render data to second spreadsheet through google script

I have code which succesfully render the data in spreadsheet. it is below
//Function to insert data in the sheet on clicking the submit button
var submissionSSKey = '1BkZoHkyjfv2H_3uuvZ6ltgXCD0WdwMwirLqcJ8__oDY';
function insertInStyleSheet(e)
{
var app = UiApp.getActiveApplication();
var name = e.parameter.name;
var message = e.parameter.message;
app.getElementById('info').setVisible(true).setStyleAttribute('color','red');
var sheet = SpreadsheetApp.openById(submissionSSKey).getActiveSheet(); //What i have to do here ?????
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 2).setValues([[name,message]]);
return app;
}
Now what i have to do ?
I have opened another sheet in (Sheet2). And i have to render data in that sheet (Currently it is rendering in the same sheet (Sheet1)).
How to render it sheet2 ?
Instead of getActive() use getSheetByName(name).

Google spreadsheet Script Create Data Validation in certain range

I'm trying this script to create data validation but it's always doesn't work
function test_validation()
{
var Spread = SpreadsheetApp.getActiveSpreadsheet();
var Sheet = Spread.getSheetByName('Sheet1');
var validate1 = Sheet.getRange("A1").getDataValidation();
Logger.log(validate1.getCriteria());
Logger.log(validate1.getCriteriaValues());
var option = new Array();
option[0]="true";
option[1]="1";
option[2]="2";
option[3]="3";
var criteria="ITEM_IN_LIST";
var helpText="Test Help Text"
var Combobox = Sheet.getRange("A2").getDataValidation();
//The line below display error
//"Cannot find method (class)setCriteria(string,String[]). "
Combobox.setCriteria(criteria,option);
Combobox.setHelpText(helpText);
var validate2 = Sheet.getRange("A2").setDataValidation(Combobox);
Logger.log(Sheet.getRange("A2").getDataValidation().getCriteria());
Logger.log(Sheet.getRange("A2").getDataValidation().getCriteriaValues());
}
Thanks in advance.
By now, some functions like getDataValidation() are not working anymore, instead use:
function test()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var option = new Array();
option[0]="0";
option[1]="1";
option[2]="2";
option[3]="3";
var dv = SpreadsheetApp.newDataValidation();
dv.setAllowInvalid(false);
dv.setHelpText("Some help text here");
dv.requireValueInList(option, true);
sheet.getRange("A3").setDataValidation(dv);
}
I found the answer finally in issue 2680
the working code
function test()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var option = new Array();
option[0]="0";
option[1]="1";
option[2]="2";
option[3]="3";
var dv = sheet.getRange("A3").getDataValidation();
dv.setAllowInvalidData(false);
dv.setHelpText("Some help text here");
dv.setCriteria(SpreadsheetApp.DataValidationCriteria.ITEM_IN_LIST,true,option );
sheet.getRange("A3").setDataValidation(dv);
}
Working example from 2021:
function set_data_validation() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dest_range = ss.getActiveSheet().getRange('A1:A10');
var list_range = ss.getSheetByName('List').getRange('A1:A');
var rule = SpreadsheetApp.newDataValidation()
.requireValueInRange(list_range)
.setAllowInvalid(false)
.build();
var rules = dest_range.getDataValidations().map(x=>[rule]);
dest_range.setDataValidations(rules);
}
It will set data validation 'List from a range' for cells 'A1:A10' on current sheet. The range is column 'A' on a sheet with name 'List'.