通过Google表单提交上的API调用使自定义函数更新单元格

时间:2019-05-02 22:12:32

标签: google-apps-script google-sheets google-form

我创建了一个链接到Google表格的Google表单。提交后,表单中的数据将更新链接表中的A-D列。现在,我希望自定义脚本在提交时调用外部API,并将响应中的数据写入E列。我试图调用weather API,以便在用户提交表单时记录天气数据。

下面是我用来从公共METAR API获取温度的函数,当我从打开的Google表格文档中的单元格调用它时,它可以正常工作。我无法从Google文档中得到的是如何在表单提交时触发它,并将其链接到E列和当前表单答案行。据我了解,不可能从单元格调用此函数,并且我将需要以某种方式引用脚本中单元格的位置(行触发脚本+ E列)?

function GetMETAR() {
  var url = 'https://avwx.rest/api/metar/KJFK?options=&format=json&onfail=cache';
  var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
  var json = response.getContentText();
  var data = JSON.parse(json);
  var tempr = data.temperature.value;
  return tempr;
}

2 个答案:

答案 0 :(得分:0)

尝试一下:

function GetMETAR(name,cell) {
  var name=name || 'Sheet2';//if you don't want to use the parameters you can set these defaults
  var cell=cell || 'B4';
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName(name);
  var rg=sh.getRange(cell);
  var url = 'https://avwx.rest/api/metar/KJFK?options=&format=json&onfail=cache';
  var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
  var json = response.getContentText();
  var data = JSON.parse(json);
  var tempr = data.temperature.value;
  rg.setValue(tempr);//cell that you want the data to go to.
}

答案 1 :(得分:0)

感谢@Cooper,这是我工作的最终代码:

function GetMETAR() {
  var ss=SpreadsheetApp.getActiveSheet();//set active sheet where form answers are stored 
  var lr = ss.getLastRow();//since form pastes last answer to last row we get its number
  var rg = ss.getRange(lr,8,1,5);//here I set range where I will paste info from API CALL
  var url = 'https://avwx.rest/api/metar/UUWW?options=&format=json&onfail=cache';//API url
  var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});//API call
  var json = response.getContentText();//response JSON to text
  var data = JSON.parse(json);//JSON text parse
  var tempr = data.temperature.value;//parsing values
  var wind_spd = data.wind_speed.value;
  var baro = data.altimeter.value;
  var dew = data.dewpoint.value;
  var wind_dir = data.wind_direction.value;
  var values = [[tempr,wind_spd,wind_dir,baro,dew]];//cobining values in array to paste
  rg.setValues(values);//pasting in range
}

脚本设置为在表单提交时触发