如何在v4中更新我的Google表格? [英] How do I update my google sheet in v4?

查看:170
本文介绍了如何在v4中更新我的Google表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是谷歌表格v4中的新成员,我只想知道如何在v4中更新我的谷歌表格。我正在使用 Nodejs ,以下是我正在使用的代码示例链接方法:spreadsheets.values.update

解决方案

您可以使用链接。在你的情况下,组合Quickstart和示例脚本可能对你有用。示例脚本如下。



在此示例脚本中,将示例文本的文本导入到单元格 a1 Sheet1



示例脚本:



  var fs = require('fs'); 
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

//如果修改这些范围,请删除以前保存的凭据
//〜〜/ .credentials / sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive'];
var TOKEN_DIR =(process.env.HOME || process.env.HOMEPATH ||
process.env.USERPROFILE)+'/.credentials/';
var TOKEN_PATH = TOKEN_DIR +'sheets.googleapis.com-nodejs-quickstart.json';

//从本地文件加载客户机密。
fs.readFile('client_secret.json',function processClientSecrets(err,content){
if(err){
console.log('Error loading client file:'+ err) ;
return;
}
//使用已加载的凭证授权客户端,然后调用
// Google Sheets API
authorize(JSON.parse(content ),valuesUpdate);
});

/ **
*用给定的凭证创建一个OAuth2客户端,然后执行
*给定的回调函数。
*
* @param {对象}凭据授权客户端凭据。
* @param {function} callback与授权客户端进行通话的回调。
* /
函数authorize(credentials,callback){
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris [0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId,clientSecret,redirectUrl);

//检查我们以前是否存储过令牌。
fs.readFile(TOKEN_PATH,function(err,token){
if(err){
getNewToken(oauth2Client,callback);
} else {
oauth2Client。 credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}

/ **
*在提示用户授权后获取并存储新令牌,然后
*使用授权的OAuth2客户端执行给定的回调。
*
* @param {google.auth.OAuth2} oauth2Client获取令牌的OAuth2客户端。
* @param {getEventsCallback}回调与授权的
*客户端进行通话的回调。
* /
函数getNewToken(oauth2Client,回调){
var authUrl = oauth2Client.generateAuthUrl({
access_type:'offline',$ b $ scope:SCOPES
});
console.log('通过访问此URL授权此应用程序:',authUrl);
var rl = readline.createInterface({
input:process.stdin,
output:process.stdout
});
rl.question('从该页面输入代码:',function(code){
rl.close();
oauth2Client.getToken(code,function(err,token) {
if(err){
console.log('尝试检索访问令牌时发生错误,错误);
返回;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}

/ **
*将令牌存储到磁盘将在以后的程序执行中使用。
*
* @param {Object}标记要存储到磁盘的标记。
* /
函数storeToken(令牌){
尝试{
fs.mkdirSync(TOKEN_DIR);
} catch(err){
if(err.code!='EEXIST'){
throw err;
}
}
fs.writeFile(TOKEN_PATH,JSON.stringify(token));
console.log('Token stored to'+ TOKEN_PATH);
}

函数valuesUpdate(auth){
var sheets = google.sheets('v4');
var request = {
//要更新的电子表格的ID。
spreadsheetId:'my-spreadsheet-id',// TODO:更新占位符值。

//要更新的值的A1符号。
范围:'Sheet1!a1:a1',// TODO:更新占位符值。

//输入数据应如何解释。
valueInputOption:'RAW',// TODO:更新占位符值。

resource:{'values':[['sample text']]},

auth:auth,
};

sheets.spreadsheets.values.update(request,function(err,response){
if(err){
console.error(err);
return ;
}

// TODO:更改下面的代码以处理`response`对象:
console.log(JSON.stringify(response,null,2));
});

$ / code>



重要提示:




  • 请在上面的脚本中将 my-spreadsheet-id 修改为您的。

  • 本示例脚本假设快速入门的脚本工作正常。

  • 在运行Quickstart脚本之后,在运行上述示例脚本之前,请删除 sheets.googleapis.com-nodejs-quickstart.json 一次。删除文件后,请运行上述脚本。这样,就可以检索包含新范围的刷新标记并用于更新值。

  • 如果要使用此脚本,请使用googleapis v24或更低版本。因为最新版本不起作用。因为发生了以下错误,即使设置了 valueInputOption 也是如此。
    $ b

    • 错误:'valueInputOption'是必需的,但未指定

    • 我相信这个错误会在不久的将来被修改。 $ b



如果我误解了您的问题,我很抱歉。

I am new in google sheets v4 and I just want to know how can I update my google sheet in v4. I am using Nodejs and following is the code sample link which I am using Method: spreadsheets.values.update

解决方案

You can use the sample script of the link. In you case, combining Quickstart and the sample script may be useful for you. The sample script is as follows.

In this sample script, the text of sample text is imported to the cell a1 of Sheet1.

Sample script :

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the
  // Google Sheets API.
  authorize(JSON.parse(content), valuesUpdate);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

function valuesUpdate(auth) {
  var sheets = google.sheets('v4');
  var request = {
    // The ID of the spreadsheet to update.
    spreadsheetId: 'my-spreadsheet-id',  // TODO: Update placeholder value.

    // The A1 notation of the values to update.
    range: 'Sheet1!a1:a1',  // TODO: Update placeholder value.

    // How the input data should be interpreted.
    valueInputOption: 'RAW',  // TODO: Update placeholder value.

    resource: {'values': [['sample text']]},

    auth: auth,
  };

  sheets.spreadsheets.values.update(request, function(err, response) {
    if (err) {
      console.error(err);
      return;
    }

    // TODO: Change code below to process the `response` object:
    console.log(JSON.stringify(response, null, 2));
  });
}

IMPORTANT :

  • Please modify my-spreadsheet-id to yours in above script.
  • This sample script supposes that the script of Quickstart works fine.
  • After run the script of Quickstart, please remove sheets.googleapis.com-nodejs-quickstart.json once, before run the above sample script. After remove the file, please run the above script. By this, the refresh token with the new scopes is retrieved and it is used for updating values.
  • If you want to use this script, please use googleapis v24 or less. Because the latest version doesn't work. Because the following error occurs, even if valueInputOption is set.
    • Error: 'valueInputOption' is required but not specified
    • I believe that this error will be modified in the near future.

If I misunderstand your question, I'm sorry.

这篇关于如何在v4中更新我的Google表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆