简体   繁体   English

在项目中使用Google Apps脚本功能

[英]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. 我是Google Apps脚本的新手,并且很好奇如何使用自己项目中创建的函数。 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. 它仅需要2个参数,并使用该数据在电子表格中添加一行。 I have deployed it as a web app, but I'm not sure how to use this function in an environment like JSFiddle . 我已经将其部署为Web应用程序,但是我不确定如何在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. 电子表格绑定脚本在服务器端运行,并且您使用的SpreadsheetApp.getActiveSheet()方法仅在电子表格绑定脚本的上下文中起作用,因为这是脚本实际“看到”活动电子表格的唯一情况。 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. 将其部署为Web应用程序时,您必须使用例如SpreadsheetApp.openById('spreadsheet ID')方法来告诉脚本必须查看哪个电子表格。

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. 但是即使这样做,也不允许在Google环境之外使用此类代码(例如,在JS小提琴中),因为SpreadsheetApp特定于Google Apps服务。

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. 您必须记住,Google Apps脚本基于 JavaScript,但不是“普通” JavaScript,它使用了许多仅与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 电子表格中用作数据服务器的代码如下:(这是作为无用户界面的Webapp部署的。它作为服务运行

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. 您可以通过其url +参数调用此服务,它将在电子表格中获取/设置值。 This is a basic example but it works nicely. 这是一个基本示例,但效果很好。

below it the webapp code of the Ui that uses this service in this spreadsheet 在其下方,使用此电子表格中的此服务的Ui的webapp代码

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "如何在谷歌应用脚​​本函数中使用模态表单数据?" - How to use the modal form data in the google apps script functions? 许多数学函数在 Google Sheets Apps 脚本中不可用。 要使用 JavaScript 功能,是否有可用的完整指南 - Many math functions are not available in Google Sheets Apps Script. To use JavaScript functions, is there any complete guide available Google Apps脚本功能的最佳实践 - google apps script functions best practtice 功能范围规则(Google Apps脚本项目) - Function Scope Rules (Google Apps Script Project) 如何在Google Apps脚本Web应用程序中使用多种样式的CSS项目文件? - How do I use multiple styles of CSS project files in the Google Apps Script Web application? 如何在Google Apps脚本中使用CheckBox小部件? - How to use checkBox widget in Google apps script? 如何将 sessionStorage 与 JS 和 Google Apps Script 一起使用? - How use sessionStorage with JS and Google Apps Script? 如何在谷歌应用脚本上使用 NumberFormat function - How use a NumberFormat function on google apps script 如何在coffeescript中为Google Apps脚本生成全局的,命名的javascript函数 - How to generate global, named javascript functions in coffeescript, for Google Apps Script Google Apps 脚本没有为所有人加载函数,只有我 - Google Apps Script Not Loading Functions for Everyone, only me
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM