4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Google Sheets クイックスタートが5分でできない

Last updated at Posted at 2019-04-01

引用

Complete the steps described in the rest of this page, and in about five minutes you'll have a simple Node.js command-line application that makes requests to the Google Sheets API.

5分でできるそうです。

できなかったので、上手くいったソースコードを貼っておきます。
下の方に、解決するまでのエラー内容書いてます。興味のある方はどうぞ。
下記をコピペで上手くいくと思います。
step1,2は上手くいっている前提です。

var fs = require('fs')
var readline = require('readline')
var { google } = require('googleapis')
var { OAuth2Client } = 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.readonly']
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), listMajors)
})

/**
 * 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 oauth2Client = new OAuth2Client(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), err => {
    if (err) return console.error(err)
    console.log('Token stored to', TOKEN_PATH)
  })
}

/**
 * Print the names and majors of students in a sample spreadsheet:
 * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 */
function listMajors(auth) {
  var sheets = google.sheets('v4')

  sheets.spreadsheets.values.get(
    {
      auth: auth,
      spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
      range: 'Class Data!A2:E'
    },
    function(err, response) {
      if (err) {
        console.log('The API returned an error: ' + err)
        return
      }
      var rows = response.data.values
      if (rows.length == 0) {
        console.log('No data found.')
      } else {
        console.log('Name, Major:')
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i]
          // Print columns A and E, which correspond to indices 0 and 4.
          console.log('%s, %s', row[0], row[4])
        }
      }
    }
  )
}

これで上手くいくと思います。失敗したら、教えてください。
ステップ3をやった時に出力されたエラーの解決法をまとめました。

#"TypeError: googlAuth is not a constructor"
github
https://github.com/googleapis/google-auth-library-nodejs/issues/251

I had the same issue using the Node.js docs and was able to resolve by importing as:
const { GoogleAuth } = require('google-auth-library');


Node.jsドキュメントを使用しても同じ問題があり、次のようにインポートすることで解決できました。

const { GoogleAuth } = require('google-auth-library');

次は、別のエラーが出ます。
#TypeError: auth.OAuth2 is not a constructor
github
https://github.com/googleapis/google-auth-library-nodejs/issues/251

Worked on this a bit more last night and rather than importing via:
const { GoogleAuth } = require('google-auth-library');
I was able to get the example to semi-work by importing OAuth2Client directly via:
const { OAuth2Client } = require('google-auth-library');


次のようにしてOAuth2Clientを直接インポートすることで、この例を半動作させることができました。


const { OAuth2Client } = require('google-auth-library');

#Cannot read property 'length' of undefined
最後のエラーです。私と同じ状況なら、121行目のあたり、rows.lenthでエラーが出ているはずです。


var rows = response.values
if (rows.length == 0) {

一回、responseをみてみます。

console.log(response)

configとかurlとかvaluesとか出てくると思います。valuesを抜粋して記載します。


data:
   { range: '\'Class Data\'!A2:E101',
     majorDimension: 'ROWS',
     values:
      [ [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array],
        [Array] ] },

どうやら、valuesはdataの中にあるので、プログラムを書き換えます。


var rows = response.data.values
if (rows.length == 0) {

これで解決するはずです。

4
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?