Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9409

Google Sheets APIで誰でも編集できるスプレッドシートを作成する(Node.js / TypeScript)

$
0
0
結論 Google Sheets API だけじゃなくて、Google Drive API も使う const sheets = google.sheets({ version: "v4", auth: oAuth2Client }); const drive = google.drive({ version: "v3", auth: oAuth2Client }); // スプレッドシートを作成する const createdSheet = await sheets.spreadsheets.create(); // Google Drive APIでスプレッドシートの権限を作成する await drive.permissions.create({ fileId: createdSheet.data.spreadsheetId, requestBody: { type: "anyone", role: "writer", }, }); // 誰でも編集できるスプレッドシートのURL console.log(createdSheet.data.spreadsheetUrl); 動くサンプル credential.jsonとtoken.jsonはあらかじめ作成してある前提です。 トークンの生成がまだの方はこちらのドキュメントを参考に、クレデンシャルのダウンロードとトークンの生成を行ってください。 https://developers.google.com/sheets/api/quickstart/nodejs import { promises as fs } from "fs"; import { google } from "googleapis"; (async () => { const credentials: GCPCredentials = await fs .readFile(`${__dirname}/../credentials.json`) .then((b) => b.toString()) .then((s) => JSON.parse(s)); const { client_id, client_secret, redirect_uris } = credentials.installed; const oAuth2Client = new google.auth.OAuth2( client_id, client_secret, redirect_uris[0] ); const token = await fs .readFile(`${__dirname}/../token.json`) .then((b) => b.toString()) .then((s) => JSON.parse(s)); oAuth2Client.setCredentials(token); const sheets = google.sheets({ version: "v4", auth: oAuth2Client }); const drive = google.drive({ version: "v3", auth: oAuth2Client }); const createdSheet = await sheets.spreadsheets.create(); await drive.permissions.create({ fileId: createdSheet.data.spreadsheetId, requestBody: { type: "anyone", role: "writer", }, }); console.log(createdSheet.data.spreadsheetUrl); })(); type GCPCredentials = { installed: { client_id: string; project_id: string; auth_uri: string; token_uri: string; auth_provider_x509_cert_url: string; client_secret: string; redirect_uris: string[]; }; };

Viewing all articles
Browse latest Browse all 9409

Trending Articles