PHP Google_Service_Sheetsでシートをコピーするには?

ショコラ
ショコラ

PHP Google_Service_Sheetsでシートをコピーするには?

やりたい事は、元のシートをコピーしてそこに値を書き込み印刷します。
その途中。

もっさん先輩
もっさん先輩

ひとまず、スプレッドシートを取得する

$google_credentials_json = "あのグーグルのJSON形式の文字列";
$google_sheet_id = "シートID(URLのところ)";

$client = new \Google_Client();
$client->addScope( \Google_Service_Sheets::SPREADSHEETS );

// 認証
$auth = tempnam(sys_get_temp_dir(),'auth-');
file_put_contents($auth,$google_credentials_json);
$client->setAuthConfig($auth);
unlink($auth);

$service = new \Google_Service_Sheets($client);

$spreadsheet = $service->spreadsheets->get($google_sheet_id);

タイトルからコピーするシートIDを取得します。

$sheet_title = 'シートタイトル'; // これでタイトルを検索する
$sheet_id = null;
foreach ($spreadsheet->getSheets() as $i => $sheet) {
  if ($sheet_title == $sheet->properties->title) {
    $sheet_id = $sheet->properties->sheetId;
    break;
  }
}
// シート無し
if (is_null($sheet_id)) {
  return false;
}

Google_Service_Sheets_CopySheetToAnotherSpreadsheetRequest を作成してコピーします。

// シートをコピーする
$request = new \Google_Service_Sheets_CopySheetToAnotherSpreadsheetRequest();
$request->destinationSpreadsheetId = $google_sheet_id; // コピー先
$result = $service->spreadsheets_sheets->copyTo($google_sheet_id,$sheet_id,$request);

// シートIDダンプとタイトルをダンプ
dd( $result->sheetId, $result->title );

以上

関連記事

Scroll to Top