質問:
Node.js で Google Spreadsheet Sheet API を用いてシートにデータを書き込むにはどうすれば良いか?
答え:
Node.js Quickstart
の例を次のように更新した後、Terminal で $ node index.js
とします。
node
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'; 6const spreadsheetId = 'spreadsheet の URL から ID を抜き出す'; 7 8 9fs.readFile('credentials.json', (err, content) => { 10 if (err) return console.log('Error loading client secret file:', err); 11 authorize(JSON.parse(content), readAndWrite); 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 19 fs.readFile(TOKEN_PATH, (err, token) => { 20 if (err) return getNewToken(oAuth2Client, callback); 21 oAuth2Client.setCredentials(JSON.parse(token)); 22 callback(oAuth2Client); 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 // Store the token to disk for later program executions 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 51function readAndWrite(auth) { 52 const sheets = google.sheets({version: 'v4', auth}); 53 54 // read 55 sheets.spreadsheets.values.get({ 56 spreadsheetId, 57 range: 'Data!A1:E2', 58 }, (err, res) => { 59 if (err) return console.log('The API returned an error: ' + err); 60 const rows = res.data.values; 61 if (rows.length) { 62 rows.map((row) => { 63 console.log(`${row[0]}`); 64 }); 65 } else { 66 console.log('No data found.'); 67 } 68 }) 69 70 // write 71 const request = { 72 spreadsheetId, 73 resource: { 74 valueInputOption: "USER_ENTERED", 75 data : [ 76 { 77 range: "Data!A1:A3", 78 values: [ 79 ["A1"],["A2"],["A3"] 80 ] 81 }, 82 { 83 range: "Data!B1:B3", 84 values: [ 85 ["B1"],["B2"],["B3"] 86 ] 87 } 88 ] 89 } 90 } 91 92 sheets.spreadsheets.values.batchUpdate(request); 93 94} 95 96module.exports = { 97 SCOPES, 98 readAndWrite, 99};
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。