我正在试用 Google 的 Cloud Functions 服务,我想阅读和编写 Google 电子表格,但似乎找不到任何示例或方法来执行此操作。
我的问题源于这样一个事实,即 Google 云函数的示例 javascript 是:
exports.helloWorld = function helloWorld (req, res) {
res.send(`Hello ${req.body.name || 'World'}!`);
};
这行得通,但我想以谷歌为例,从谷歌电子表格中读取:
gapi.load('client:auth2', initClient);
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
});
}
有谁知道这是否可行或显示如何执行类似操作的示例?
最佳答案
以下是我如何使用 Google Cloud Functions 完成的。我认为 OAuth 不太适合,因为 Cloud Functions 通常在无人值守的情况下运行。幸运的是,有服务帐户,用于机器对机器的通信。
1。在您的 Cloud 项目中创建一个服务帐户
2。保存服务帐号 key
在第 1 步中,将 JSON 格式的 key 文件下载到您的计算机上。将其保存在您的项目目录中并将其重命名为 credentials.json
。
3。创建 API key
4。保存 API key
将步骤 3 中的 API key 复制并保存到项目目录中名为 api_key.json
的文件中。它应该看起来像这样:
{
"key": "<PASTE YOUR API KEY HERE>"
}
5。授予对服务帐户的电子表格访问权限
与在第 1 步中创建的服务帐户电子邮件共享电子表格。
6。调用 Google 的表格 API
这是我的代码,每次调用 Cloud Function 时都会向电子表格附加一行。
const {google} = require('googleapis');
exports.reply = (req, res) => {
var jwt = getJwt();
var apiKey = getApiKey();
var spreadsheetId = '<PASTE YOUR SPREADSHEET ID HERE>';
var range = 'A1';
var row = [new Date(), 'A Cloud Function was here'];
appendSheetRow(jwt, apiKey, spreadsheetId, range, row);
res.status(200).type('text/plain').end('OK');
};
function getJwt() {
var credentials = require("./credentials.json");
return new google.auth.JWT(
credentials.client_email, null, credentials.private_key,
['https://www.googleapis.com/auth/spreadsheets']
);
}
function getApiKey() {
var apiKeyFile = require("./api_key.json");
return apiKeyFile.key;
}
function appendSheetRow(jwt, apiKey, spreadsheetId, range, row) {
const sheets = google.sheets({version: 'v4'});
sheets.spreadsheets.values.append({
spreadsheetId: spreadsheetId,
range: range,
auth: jwt,
key: apiKey,
valueInputOption: 'RAW',
resource: {values: [row]}
}, function(err, result) {
if (err) {
throw err;
}
else {
console.log('Updated sheet: ' + result.data.updates.updatedRange);
}
});
}
希望这对您有所帮助!
关于javascript - 如何在谷歌云功能中使用谷歌表格 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448029/