Sato's Tech Memo

備忘録と情報共有を兼ねたメモです

Google Spread Sheetを操作する方法

f:id:satoko_szk:20181105005600p:plain

Google API Consoleでサービスアカウントキーを作成

  1. Google Cloud Platform へアクセスする。
  2. 既存のプロジェクトを選択、または新規プロジェクトを作成。
  3. 「認証情報」→「認証情報の作成」→「サービスアカウントキー」
  4. 作成すると、キーがダウンロードされるので保管する。
認証情報の種類 サービスアカウントキー
サービスアカウントの種類 App Engine default service account
キーのタイプ JSON

スプレッドシートの共有を作成

  1. 操作したいスプレッドシートを開く
  2. 「ファイル」→「共有」
  3. ダウンロードした、キーファイル内の client_email を共有先として登録する。

スプレッドシートを操作する(PHPの場合)

参考:


共有サーバで使うので、ライブラリをダウンロードしてくる方式で。

  1. Releases · googleapis/google-api-php-client · GitHubからgoogle-api-php-client-[RELEASE_NAME].zipをダウンロード。
  2. 以下のようなソース。
<?php
require_once 'google-api-php-client-2.2.2/vendor/autoload.php';

$SPREADSHEET_ID="xxxxxxxxxxxxxxxxxxxxxxxx";

$client = new Google_Client();
$client->setAuthConfig('SpreadApiAuth.json');     //ダウンロードしたキーファイルのパス
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
$client->setApplicationName("Test");    //適当な名前

$service = new Google_Service_Sheets($client);

// A:D の範囲を取得
$response = $service->spreadsheets_values->get($SPREADSHEET_ID, 'Sheet1!$A:$D');
$values = $response->getValues();

if (count($values) == 0) {
  print "No data found.\n";
}else{
  print count($values);
}
foreach ($values as $row) {
	printf('%s, %s\n', $row[0], $row[1]);
}
?>