官方範例 Quickstart for Sheets API with the PHP Client 是使用 OAuth 認證,如果單純用程式處理 google sheet 沒有使用者參與的情形,可以參考以下方式
composer require google/apiclient:"^2.0"
gcs_civil.json
就是之前保留的檔案
function getClient()
{
$client = new \Google_Client();
$client->setApplicationName('Qucikstart');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS_READONLY]);
$client->setAccessType('offline');
$jsonAuth = file_get_contents(__DIR__ . "/../../../config/gcs_civil.json");
$client->setAuthConfig(json_decode($jsonAuth, true));
return $client;
}
function get($client, $spreadSheetId, $range): array
{
$service = new \Google_Service_Sheets($client);
$response = $this->service->spreadsheets_values->get($spreadSheetId, $range);
return $response->getValues();
}
$client = getClient();
$datas = get($client, 'sheet_id', 'tab_name!A2:E')
補充,如果儲存格只到 B 欄有資料,那陣列會是 2 (只有 A, B),長度並非固定是 5
function create($client) {
$service = new \Google_Service_Sheets($client);
$spreadsheet = new \Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => 'test-sheet'
]
]);
$spreadsheet = $service->spreadsheets->create($spreadsheet, [
'fields' => 'spreadsheetId'
]);
printf("Spreadsheet ID: %s\n", $spreadsheet->spreadsheetId);
}
function update($client, $spreadSheetId) {
$service = new \Google_Service_Sheets($client);
$values = [
['col-a', 'col-b', 'col-c'],
// other row
];
$tab = 'tab-name';
$rowCount = count($values);
$range = "'{$tab}'!A1:C{$rowCount}";
$updateBody = new \Google_Service_Sheets_ValueRange([
'range' => $range,
'majorDimension' => 'ROWS',
'values' => $values,
]);
$result = $service->spreadsheets_values->update($spreadSheetId, $range, $updateBody, ['valueInputOption' => 'raw']);
}
function clear($client, $spreadSheetId) {
$service = new \Google_Service_Sheets($client);
$range = "'test'!A1:C";
$requestBody = new \Google_Service_Sheets_ClearValuesRequest();
$response = $service->spreadsheets_values->clear($spreadSheetId, $range, $requestBody)
}
trick
Basics 文件中 The Command-Line Test Runner 有結果縮寫的代表意義 Error 是異常,Fail 是斷言錯誤 有些 Assertions 的判斷方式要注意,還是要看手冊跟實作方法才能確定,例如 assertEmpty(['', '']) Test Dependencies 測試的執行流程有獨立性,和平常的執行流程不同;如果不同測試方法有相依,例如需要使用前一個測試方法運算果的資料,可以用 @depends 來做相依的測試 Config
Oct 26, 2021指派 new 函式 new 是一個內建的函式,用來建構變數,new(T) 會申請一塊記憶體,以 T 的零值初始化,並回傳指標 *T p := new(int) fmt.Println(*p) // 0 *p = 2 fmt.Println(*p) // 2 new 是內建的函式,不是關鍵字,所以能在函式中重新宣告
Jun 26, 2021or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up