質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Q&A

解決済

2回答

2344閲覧

Googleスプレットシートにnode.jsで書き込みがうまくいかない

ices_sinon

総合スコア479

Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

0グッド

1クリップ

投稿2019/06/06 03:18

Googleスプレットシートにnode.jsで書き込みたいのですがエラーも表示されずうまくいきません。
スプレットシートの値の取得はできるのですが書き込むどうしたらよいでしょうか。

index.js

1const fs = require('fs'); 2const readline = require('readline'); 3const {google} = require('googleapis'); 4const SCOPES = ['https://www.googleapis.com/auth/spreadsheets']; 5const TOKEN_PATH = 'token.json'; 6 7 8fs.readFile('credentials.json', (err, content) => { 9 if (err) return console.log('Error loading client secret file:', err); 10 authorize(JSON.parse(content), listMajors,Listwrite); 11}); 12 13 14function authorize(credentials, callback) { 15 const {client_secret, client_id, redirect_uris} = credentials.installed; 16 const oAuth2Client = new google.auth.OAuth2( 17 client_id, client_secret, redirect_uris[0]); 18 fs.readFile(TOKEN_PATH, (err, token) => { 19 if (err) return getNewToken(oAuth2Client, callback); 20 oAuth2Client.setCredentials(JSON.parse(token)); 21 callback(oAuth2Client); 22 }); 23} 24 25 26function getNewToken(oAuth2Client, callback) { 27 const authUrl = oAuth2Client.generateAuthUrl({ 28 access_type: 'offline', 29 scope: SCOPES, 30 }); 31 console.log('Authorize this app by visiting this url:', authUrl); 32 const rl = readline.createInterface({ 33 input: process.stdin, 34 output: process.stdout, 35 }); 36 rl.question('Enter the code from that page here: ', (code) => { 37 rl.close(); 38 oAuth2Client.getToken(code, (err, token) => { 39 if (err) return console.error('Error while trying to retrieve access token', err); 40 oAuth2Client.setCredentials(token); 41 42 fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { 43 if (err) return console.error(err); 44 console.log('Token stored to', TOKEN_PATH); 45 }); 46 callback(oAuth2Client); 47 }); 48 }); 49} 50 51 52function listMajors(auth) { 53 const sheets = google.sheets({version: 'v4', auth}); 54 sheets.spreadsheets.values.get({ 55 spreadsheetId: '*************', 56 range: 'シート1', 57 }, (err, res) => { 58 if (err) return console.log('The API returned an error: ' + err); 59 const rows = res.data.values; 60 if (rows.length) { 61 rows.map((row) => { 62 console.log(`${row[0]}`); 63 }); 64 } else { 65 console.log('No data found.'); 66 } 67 }); 68} 69 70function Listwrite(spreadsheetId, range, valueInputOption, _values){ 71 let values =[ 72 [ 73 1 74 ], 75 ]; 76 values = _values; 77 78 let resource = { 79 values, 80 }; 81 const sheets = google.sheets({ 82 version: 'v4', auth 83 }); 84 sheets.spreadsheets.values.append({ 85 spreadsheetId: '*************************', 86 range: 'シート1', 87 valueInputOption: 'RAW' , 88 resource: "hello world", 89 }, (err,result) => { 90 if (err) console.log(err); 91 console.log(`${result.updates.updatedCells} cells appended.` + 'OK'); 92 }); 93}

上記のListwriteの関数内で書き込みを行おうと考えています。
スプレットシートにhello worldと書き込みたいです。

アドバイスをしてくれると助かります。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

自己解決

appendのコードを書き直して、token.jsonを発行しなおしたら出力できるようになりました。

const fs = require('fs'); const readline = require('readline'); const {google} = require('googleapis'); // If modifying these scopes, delete token.json. const SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive']; // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. const TOKEN_PATH = 'token.json'; // Load client secrets from a local file. fs.readFile('credentials.json', (err, content) => { if (err) return console.log('Error loading client secret file:', err); // Authorize a client with 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) { const {client_secret, client_id, redirect_uris} = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0]); // Check if we have previously stored a token. fs.readFile(TOKEN_PATH, (err, token) => { if (err) return getNewToken(oAuth2Client, callback); oAuth2Client.setCredentials(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 for the authorized client. */ function getNewToken(oAuth2Client, callback) { const authUrl = oAuth2Client.generateAuthUrl({ access_type: 'offline', scope: SCOPES, }); console.log('Authorize this app by visiting this url:', authUrl); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question('Enter the code from that page here: ', (code) => { rl.close(); oAuth2Client.getToken(code, (err, token) => { if (err) return console.error('Error while trying to retrieve access token', err); oAuth2Client.setCredentials(token); // Store the token to disk for later program executions fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { if (err) return console.error(err); console.log('Token stored to', TOKEN_PATH); }); callback(oAuth2Client); }); }); } /** * Prints the names and majors of students in a sample spreadsheet: * @see https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit * @param {google.auth.OAuth2} auth The authenticated Google OAuth client. */ function listMajors(auth) { const sheets = google.sheets({ version: 'v4', auth }); sheets.spreadsheets.values.append({ spreadsheetId: '************', range: 'シート1', valueInputOption: 'RAW', insertDataOption: 'INSERT_ROWS', resource: { values: [ ["hello", "world"] ], }, },(err, result) => { if (err) return console.log(err); console.log('%d cells updated.', result.totalUpdatedCells); }); }

投稿2019/06/07 01:46

ices_sinon

総合スコア479

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

書き込みができないというのは読み込み専用のスコープでアクセスしている事が原因ではないでしょうか?
以下の記事をご参考ください。
https://www.nnn.ed.nico/questions/9490

https://stackoverflow.com/questions/38534801/google-spreadsheet-api-request-had-insufficient-authentication-scopes

投稿2019/06/06 07:26

marurunn

総合スコア702

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ices_sinon

2019/06/06 07:29

スコープの改善も行なったができませんでした。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問