LoginSignup
2
4

More than 3 years have passed since last update.

GoogleスプレッドシートAPIの小ネタ集

Last updated at Posted at 2020-01-23

はじめに

こちらの記事は、

を使ってできることの小ネタ集の記事です。

参考にした記事は、PHPでSheetsAPIを使用してGoogleスプレッドシートにデータを追記していくサンプル。です。

ですので、上記の記事の

  • プロジェクトを作る。
  • スプレッドシート作成・共有設定
  • PHPからスプレッドシート追記 > 0. githubからcloneしてライブラリ導入
  • PHPからスプレッドシート追記 > 1. プロジェクト直下にダウンロードしたJsonファイルを設置

まで同じです!

Googleスプレッドシートの値を読み込む

サンプルソース

動作確認はしていないので、エラーになったらごめんなさい。

require_once __DIR__.'/vendor/autoload.php';

class GoogleSpreadSheetClass {
    protected $service;

    protected $serviceKeyJson = 'サービスアカウントキーが書いてあるファイル.json';

    function __construct() {
        putenv('GOOGLE_APPLICATION_CREDENTIALS=' . dirname(__FILE__) . '/' . $this->serviceKeyJson);

        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Google_Service_Sheets::SPREADSHEETS);
        $client->setApplicationName('test');
        $this->service = new Google_Service_Sheets($client);
    }

    /**
     * @param string スプレッドシートID
     * @param string 最終列アルファベット
     * @param string 最終行番号
     * @return boolean 成功 or 失敗
     */
    function main($spreadSheetId, $lastColumnNumber, $lastRowNumber) {
        $lastRange = $lastColumnNumber . $lastRowNumber;

        try {
            $data = $this->service->spreadsheets_values->get($spreadSheetId, 'A1:' . $lastRange);
            var_dump($data->values);

        } catch (Exception $e) {
            return false;
        }

        return true;
    }

}

サンプルスプレッドシート

spread_sheet_sample.png

解説

spreadsheets_valuesの関数は、

  • 第一引数にスプレッドシートのID
  • 第二引数にスプレッドシートの範囲

を指定します。

スプレッドシートの範囲は、stringで「A1:D6」などと指定します。
開始から終了まで斜めで囲む感じですね。

返ってくる値

Array
(
    [0] => Array
        (
            [0] => メーカー名
            [1] => 弦の名前
            [2] => おすすめジャンル
            [3] => 価格
        )

    [1] => Array
        (
            [0] => Thomastik Infeld
            [1] => Spirocore Midium
            [2] => ジャズポップス
            [3] => 18,900+tax
        )

    [2] => Array
        (
            [0] => Thomastik Infeld
            [1] => Spirocore Light
            [2] => ジャズポップス
            [3] => 18,900+tax
        )

    [3] => Array
        (
            [0] => Pirastro
            [1] => Flexocor
            [2] => なんでも
            [3] => 28,980+tax
        )

    [4] => Array
        (
            [0] => Pirastro
            [1] => Original Flexocor
            [2] => オーケストラ
            [3] => 38,040+tax
        )

    [5] => Array
        (
            [0] => Pirastro
            [1] => The Jazzer
            [2] => ジャズ
            [3] => 28,440+tax
        )

)

スプレッドシートのファイル名を取得

コンストラクタまで一緒

$fileName = $this->service->spreadsheets->get($spreadSheetId)->properties->title;

スプレッドシートのシート名を取得

コンストラクタまで一緒。配列のインデックスは適宜調整。ループで回すなど。

$test = $this->service->spreadsheets->get($spreadSheetId);
$test->sheets[0]->properties->title;

スプレッドシートのワークシートをコピー

コンストラクタまで一緒


$requestBody = new Google_Service_Sheets_CopySheetToAnotherSpreadsheetRequest();
$requestBody->destination_spreadsheet_id = $this->spreadsheetId;
$response = $this->service->spreadsheets_sheets->copyTo($this->spreadsheetId, 0, $requestBody);

第2引数は、シートのIDになります。
シートのIDは、スプレッドシートURLの#gid=の後ろにある数値になります。
公式ドキュメント

スプレッドシートに値を書き込む

コンストラクタまで一緒

//シートの範囲
$range = 'シート1!A2:C3';

//書き込みたい値
$content = [
    ['いちご', '500'],
    ['りんご', '250'],
    ['バナナ', '250'],
];

$requestBody = new Google_Service_Sheets_ValueRange([
                'values' => $content,
               ]);

// データの入力方法
//USER_ENTERED -> 画面から入力したのと同じようになる(計算式の解釈などが入る)
//RAW -> そのまま表示されます(計算式の解釈などなし)
$params = ['valueInputOption' => 'USER_ENTERED'];

$result = $this->service->spreadsheets_values->update(
                $this->spreadsheetId,
                $range,
                $requestBody,
                $params
            );

これを作った経緯

あるデータを突っ込んで、WordPressで固定ページ作りたいということがあったので、スプレッドシートの一行ずつで固定ページを作成するような処理を書いたときにやったやつなどの小ネタ集です。

Google Spreadsheet APIに関しては、以下の記事がいろんなパターンが載っているので最強です。
【PHP】Google spreadsheet API(V4)の使い方・全25実例!

2
4
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
2
4