LoginSignup
1
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-03-08

結論

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.jsontoken.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[];
  };
};

1
0
0

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
1
0