可以使用Google Spreedsheet中的外部API调用吗?

It'*_* me 8 spreadsheet google-sheets google-spreadsheet-api

我创建了一个包含五列的Google电子表格;

一旦用户填写前三列中的值,它就必须调用第三方API并填充第四和第五列中的值(响应).

是否可以在Google Spreadsheet中为API调用编写代码?是否可以在Google电子表格中调用并获取外部API的响应?

Ama*_*uel 8

有一种方法可以进行API调用并将结果放入电子表格 - 我知道这样做的唯一方法是创建/打开目标电子表格,转到工具,然后编写脚本编辑器,并将其用作绑定脚本:

function Maestro() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //get active spreadsheet (bound to this script)
var sheet = ss.getSheetByName('mae'); //The name of the sheet tab where you are sending the info

var apiCall = 'getUpcomingConference';
var apiKey = '_____key here______';
var apiToken = '______security token______';
var url = 'http://myaccount.maestroconference.com/_access/' + apiCall +"?customer=" + apiKey + "&key=" + apiToken; //api endpoint as a string 

var response = UrlFetchApp.fetch(url); // get api endpoint
var json = response.getContentText(); // get the response content as text
var mae = JSON.parse(json); //parse text into json

Logger.log(mae); //log data to logger

var stats=[]; //create empty array to hold data points

var date = new Date(); //create new date for timestamp

//The number in brackets refers to which instance we are looking at - soonest upcoming call is [0], next after that is [1], etc.
stats.push(date); //timestamp
stats.push(mae.value.conference[0].name);
stats.push(mae.value.conference[0].scheduledStartTime);
stats.push(mae.value.conference[0].UID);

//append the stats array to the active sheet 
sheet.appendRow(stats);
}
Run Code Online (Sandbox Code Playgroud)

它需要一点接口工作但功能!它从API调用获取信息并将其放入电子表格中.


小智 5

我最近遇到了相同的要求,即读取工作表的行并按请求发送数据并记录响应。我想我会分享我在谷歌搜索后得到的结果......

function testing_this() {
    var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
    for (row in data) {
        Logger.log(data[row]);   

        var row = data[row]
        var options = {
            'method': 'post',
            'payload': { email:row[1]}
        };
        // sending to API. for example: 
        UrlFetchApp.fetch('https://your-rest-api-url/v1/customers/', options);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想获取工作表中的数据,您应该使用以下函数:

var response = UrlFetchApp.getRequest("http://your-api-url/");
    for(data in response) {
        var respData = response[data];
        // do whatever u want to do with this data...
    }
Run Code Online (Sandbox Code Playgroud)

希望它对所有面临与上述类似要求的人有用。

如果你想分叉/拉取,我已经在 github 中发布了这个脚本...

https://github.com/joshiparthin/gsheetScriptExperiments/blob/master/readAndSendToApi.js

干杯,

帕斯