Skip to content

Instantly share code, notes, and snippets.

@gundamew
Created January 19, 2021 10:45
Show Gist options
  • Save gundamew/86f87eab2c3500c9b22b067c6ddb48c3 to your computer and use it in GitHub Desktop.
Save gundamew/86f87eab2c3500c9b22b067c6ddb48c3 to your computer and use it in GitHub Desktop.
Adopted Google API client library with Laravel.
<?php
use Illuminate\Support\Carbon;
use Google_Client;
use Google_Service_Sheets;
use Google_Service_Sheets_Request;
use Google_Service_Sheets_ValueRange;
use Google_Service_Sheets_BatchUpdateSpreadsheetRequest;
class Example
{
public function handle()
{
$results = [
[/* 'cell_1', 'cell_2', ... */], // row_1
[/* 'cell_1', 'cell_2', ... */], // row_2
/* ... */
];
$this->write($results);
}
protected function write($data)
{
$client = $this->getGoogleClient();
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);
$spreadsheetId = config('digo.report.google_spreadsheet_id');
$sheetPrefix = Carbon::yesterday(config('app.timezone'))
->setTimezone('Asia/Taipei')
->format('Ymd');
foreach ($data as $key => $rows) {
$sheetTitle = implode('_', [$sheetPrefix, $key]);
if (! $this->isSheetExists($service, $spreadsheetId, $sheetTitle)) {
$this->addSheet($service, $spreadsheetId, $sheetTitle);
}
// add headers
array_unshift($rows, ['Col 1', 'Col 2', 'Col 3', 'Col 4', 'Col 5', 'Col 6']);
$range = implode('!', [$sheetTitle, 'A1:F' . count($rows)]);
$this->insertRows($service, $spreadsheetId, $range, $rows);
}
}
protected function insertRows(Google_Service_Sheets $service, $spreadsheetId, $range, array $values)
{
$values = [
'majorDimension' => 'ROWS',
'values' => $values,
];
$body = new Google_Service_Sheets_ValueRange($values);
$params = [
'valueInputOption' => 'RAW',
];
return $service->spreadsheets_values->update($spreadsheetId, $range, $body, $params);
}
protected function addSheet(Google_Service_Sheets $service, $spreadsheetId, $title)
{
$requests = [
new Google_Service_Sheets_Request([
'addSheet' => [
'properties' => [
'title' => $title,
],
]
]),
];
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
'requests' => $requests,
]);
return $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
}
// ref: https://stackoverflow.com/a/44962527
protected function isSheetExists(Google_Service_Sheets $service, $spreadsheetId, $title)
{
$spreadsheet = $service->spreadsheets->get($spreadsheetId);
$sheetsProperties = array_column($spreadsheet['sheets'], 'properties');
foreach ($sheetsProperties as $properties) {
if ($properties->getTitle() === $title) {
return true;
}
}
return false;
}
protected function getGoogleClient()
{
$client = new Google_Client();
$client->setAuthConfig(base_path('credentials.json'));
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
return $client;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment