简体   繁体   中英

Use Google Apps Script functions in project

I am very new to Google Apps Scripts and am curious how I can use functions created in my own project. For example, I have a script bound to a spreadsheet with just one function:

function addOrder(title, content) {
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.appendRow([ Date(), title, content]);
}

It simply takes 2 arguments and adds a row to the spreadsheet with that data. I have deployed it as a web app, but I'm not sure how to use this function in an environment like JSFiddle . Any help is appreciated.

Thanks

Spreadsheet bound scripts run server side and the SpreadsheetApp.getActiveSheet() method you are using will only work in the context of a spreadsheet bound script since it's the only case where the script actually "sees" an active spreadsheet. When you deploy this as a webapp you will have to tell the script which spreadsheet it must look at using for example the SpreadsheetApp.openById('spreadsheet ID') method.

But even doing so will not allow for using such a code outside of Google environment (as in JS fiddle for example) since SpreadsheetApp is specific to Google Apps service.

You have to remember that Google Apps Script is based on JavaScript but is not "plain" JavaScript , it uses a lot of specific services that work only in relation with Google Apps.


edit to answer your comment below :

the code used in the spreadsheet to work as a data server goes like this : (this is deployed as a webapp without user interface. It runs as a service

function doGet(e) {
  if(e.parameter.mode==null){return ContentService.createTextOutput("error, wrong request").setMimeType(ContentService.MimeType.TEXT)};
  var mode = e.parameter.mode;
  var value = e.parameter.value;
  var ss = SpreadsheetApp.openById('1yad5sZZt-X6bIftpR--OSyf3VZWf3Jxx8UJBhh7Arwg');
  var sh = ss.getSheets()[0];
  if(mode=='read'){
    var sheetValues =  sh.getDataRange().getValues();// get data from sheet
    var valToReturn = ContentService.createTextOutput(JSON.stringify(sheetValues)).setMimeType(ContentService.MimeType.JSON);
    return valToReturn;// send it as JSon string
    }
  if(mode=='write'){
    var val = Utilities.base64Decode(value,Utilities.Charset.UTF_8);// decode base64 and get an array of numbers
    Logger.log(val);// see it !
    var stringVal = ''; // create an empty string
    for(var n in val){
      stringVal += String.fromCharCode(val[n]);// add each character in turn
    }
    var sheetValues =  JSON.parse(stringVal);// convert the string into an object (2D array)
    Logger.log(sheetValues);// check result
    sh.getRange(1,1,sheetValues.length,sheetValues[0].length).setValues(sheetValues);// update the sheet
    return ContentService.createTextOutput(JSON.stringify(sheetValues)).setMimeType(ContentService.MimeType.JSON);// send back the result as a string
    }
  return ContentService.createTextOutput('error').setMimeType(ContentService.MimeType.TEXT);// in case mode is not 'read' nor 'write'... should not happen ! 
}

you can call this service by its url + parameters and it will get / set values in the spreadsheet. This is a basic example but it works nicely.

below it the webapp code of the Ui that uses this service in this spreadsheet

var stylePanel = {'padding':'50px', 'background':'#FFA'};
var styleButton = {'padding':'5px', 'border-radius':'5px', 'borderWidth':'1px', 'borderColor':'#DDD','fontSize':'12pt'};
var styleTextItalic = {'fontSize':'12pt','fontStyle':'italic','fontFamily':'arial,sans-serif','color':'#F00'};
var styleTextNormal = {'fontSize':'12pt','fontStyle':'normal','fontFamily':'arial,sans-serif','color':'#00F'};
var styleLabel = {'fontSize':'12pt','color':'#F00'};
var url = 'https://script.google.com/macros/s/AKfycbwPioVjYMSrmhKnJOaF2GG83dnstLWI7isU9SF1vxPV8td-g9E7/exec';
var numRow = 21;// the number of rows in the grid = number of rows in the SS + 1
;
function doGet() {
  var app = UiApp.createApplication().setTitle('url_fetch_demo');
  var panel = app.createVerticalPanel().setStyleAttributes(stylePanel);
  var headers = ['Field Name','Your answer'];// grid title
  var grid = app.createGrid(numRow+2,2);// create the grid with right size
  var wait = app.createImage('https://dl.dropboxusercontent.com/u/211279/loading3T.gif').setId('wait').setVisible(false);// get a spinner image in animated gif
  var handlerWrite = app.createServerHandler('writeSheet').addCallbackElement(grid);// 2 handlers for the buttons
  var handlerRead = app.createServerHandler('readSheet').addCallbackElement(grid);
  var Chandler = app.createClientHandler().forTargets(wait).setVisible(true);// a client handler for the spinner
  var buttonWrite = app.createButton('Write to Sheet',handlerWrite).addClickHandler(Chandler).setStyleAttributes(styleButton);
  var buttonRead = app.createButton('Read from Sheet',handlerRead).addClickHandler(Chandler).setStyleAttributes(styleButton);
  for(var n=1 ; n < numRow ; n++){
    for(var m=0 ; m < 2 ; m++){ // create all the textBoxes with names & IDs
      var textBox = app.createTextBox().setText('no value').setName('text'+n+'-'+m).setId('text'+n+'-'+m).setStyleAttributes(styleTextNormal);
    //if(m==0){textBox.setEnabled(false)};// prevent writing to left column (optional)
      grid.setWidget(n,m,textBox);// place widgets
    }
  }
  grid.setWidget(numRow,0,buttonRead).setWidget(numRow,1,buttonWrite).setWidget(numRow+1,1,wait) // place buttons
  .setWidget(0,0,app.createLabel(headers[0]).setStyleAttributes(styleLabel)) // and headers
  .setWidget(0,1,app.createLabel(headers[1]).setStyleAttributes(styleLabel));
  app.add(panel.add(grid));
  return app; // show Ui
}

function writeSheet(e){
  var app = UiApp.getActiveApplication();
  app.getElementById('wait').setVisible(false);// spinner will be hidden when fct returns
  var dataArrayImage = [];// an array to get typed values
  for(var n=1 ; n < numRow ; n++){ 
    var row=[];
    for(var m=0 ; m < 2 ; m++){
      row.push(e.parameter['text'+n+'-'+m]); // get every value in every "cell"
      var textBox = app.getElementById('text'+n+'-'+m).setStyleAttributes(styleTextItalic);// update "cells" style
      //textBox.setText('written value = '+e.parameter['text'+n+'-'+m]);// rewrite to the cells - not usefull but serves to check while debugging
    }
    dataArrayImage.push(row);// store one row(=2cells)
  }
  var UiValues = JSON.stringify(dataArrayImage);// stringfy the array
  var newValues = url+'?mode=write&value='+Utilities.base64Encode(UiValues,Utilities.Charset.UTF_8);// add to url & parameters+ encode in pure ASCII characters
  Logger.log(newValues);// check in logger
  var check = UrlFetchApp.fetch(newValues).getContent();// get back the result
  Logger.log(check);// check result = newValues sent back in bytes format
  return app;//update Ui
}

function readSheet(e){
  var app = UiApp.getActiveApplication();
  app.getElementById('wait').setVisible(false);
  var returnedValue = UrlFetchApp.fetch(url+'?mode=read').getContentText();// get data from server
  Logger.log(returnedValue);// check values
  var sheetValues = JSON.parse(returnedValue);
  for(var n=1 ; n < numRow ; n++){
    for(var m=0 ; m < 2 ; m++){
      var textBox = app.getElementById('text'+n+'-'+m).setStyleAttributes(styleTextNormal);
      textBox.setText(sheetValues[n-1][m]);// iterate and update cells values
    }
  }
return app;// update Ui
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM