【问题标题】:Use Google Apps Script functions in project在项目中使用 Google Apps 脚本函数
【发布时间】:2014-12-21 05:12:53
【问题描述】:

我对 Google Apps 脚本非常陌生,我很好奇如何使用在我自己的项目中创建的函数。例如,我有一个脚本绑定到只有一个函数的电子表格:

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

它只需要 2 个参数并使用该数据在电子表格中添加一行。我已将其部署为 Web 应用程序,但我不确定如何在 JSFiddle 这样的环境中使用此功能。任何帮助表示赞赏。

谢谢

【问题讨论】:

    标签: javascript database web-applications web google-apps-script


    【解决方案1】:

    电子表格绑定脚本在服务器端运行,您使用的SpreadsheetApp.getActiveSheet() 方法仅适用于电子表格绑定脚本的上下文,因为这是脚本实际“看到”活动电子表格的唯一情况。当您将其部署为 web 应用程序时,您必须告诉脚本它必须使用例如 SpreadsheetApp.openById('spreadsheet ID') 方法查看哪个电子表格。

    但即使这样做也不允许在 Google 环境之外使用这样的代码(例如在 JS fiddle 中),因为 SpreadsheetApp 特定于 Google Apps 服务。

    您必须记住,Google Apps 脚本基于 JavaScript,但不是“普通”JavaScript,它使用了许多仅与 Google Apps 相关的特定服务。


    编辑在下面回答您的评论:

    电子表格中用作数据服务器的代码如下所示:(这被部署为没有用户界面的 web 应用程序。它作为服务运行

    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 ! 
    }
    

    您可以通过其 url + 参数调用此服务,它将在电子表格中获取/设置值。这是一个基本示例,但效果很好。

    下面是this spreadsheet中使用该服务的UI的webapp code

    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
    }
    

    【讨论】:

    • 感谢您提供所有这些有用的信息。那么,您建议将项目添加到 google 环境之外的 google 电子表格的最佳方法是什么?谢谢。
    • @breadedturtle 您可以使用 (1) ContentService goo.gl/pIomAK 作为后端服务器或 (2) Google Sheets API goo.gl/epfT3p 将项目添加到 google 环境之外的 google 电子表格。
    • @breadturtle - 如果你有兴趣,试试这两个网址:sheet 和 webapp
    • @Sergeinsas 有没有你的 webapp 的开源代码,所以我可以确切地看到它在做什么?谢谢。
    • @AlexanderIvanov 我已成功使用 Google Sheets API 读取数据,但我仍然对如何使用它写入数据感到困惑。 (见other post)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多