Php Google Sheets API在行位置插入行
我正在使用GoogleAPI向GoogleSheet添加行。这一切都很好,但是新行正在添加到末尾(使用append方法) 我想在标题下方的顶部插入一行,在我的例子中是第2行 这是我添加到末尾的工作代码。如何指定在给定位置插入行的位置Php Google Sheets API在行位置插入行,php,google-sheets,google-sheets-api,Php,Google Sheets,Google Sheets Api,我正在使用GoogleAPI向GoogleSheet添加行。这一切都很好,但是新行正在添加到末尾(使用append方法) 我想在标题下方的顶部插入一行,在我的例子中是第2行 这是我添加到末尾的工作代码。如何指定在给定位置插入行的位置 putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $CredentialFile); $client = new \Google_Client; $client->useAp
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $CredentialFile);
$client = new \Google_Client;
$client->useApplicationDefaultCredentials();
$client->setApplicationName("MyApp");
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
ServiceRequestFactory::setInstance(new DefaultServiceRequest($accessToken));
$SheetId = "MySheetId";
$service = new \Google_Service_Sheets($client);
$sheet = $service->spreadsheets->get($SheetId);
$sheets = $sheet->getSheets();
$SheetTitle = $sheets[0]->properties->title;
$range = "{$SheetTitle}!A:D";
$values = [];
$row = [];
$row[] = "Tom";
$row[] = "Thumb";
$row[] = "tomthumb";
$row[] = "tom@thumb.com"
$values[] = $row;
$body = new \Google_Service_Sheets_ValueRange([
'values' => $values
]);
$params = [
'valueInputOption' => "RAW"
];
$result = $service->spreadsheets_values->append($SheetId, $range, $body, $params);
您使用的是根据定义将值附加到第一个空行的
如果要在不是工作表第一个空行的范围内插入值,则需要使用该方法
样本:
$range=“Sheet1!A2:D2”;
$values=数组(
排列(
“汤姆”,“拇指”,“拇指”tom@thumb.com"
)
);
$data=array();
$data[]=新的Google\u服务\u表单\u值范围(数组)(
“范围”=>$range,
“值”=>$values
)
);
$body=新Google\u服务\u工作表\u批量更新值请求(数组)(
“valueInputOption”=>“原始”,
“数据”=>$data
)
);
$result=$service->spreadsheets\u values->batchUpdate($SheetId,$body);
更新
- 如果希望插入包含数据的行,而不是将数据粘贴到现有行中,则需要先创建附加行
$request=新Google\u服务\u工作表\u批量更新ReadSheetRequest(数组)(
'请求'=>数组(
“insertDimension”=>数组(
“范围”=>数组(
“startIndex”:1,
“endIndex”:2,
“维度”:“行”,
“sheetId”:0
)
)
)
));
$request->setRequests($body);
$result=$service->spreadsheets->batchUpdate($SheetId,$request);
谢谢-我已经尝试过了,但它正在覆盖当前第2行的数据。如何使其插入新行?谢谢你看,如果你想在用值填充新行之前插入新行,你需要执行两个请求-我现在将更新我的答案来说明如何做。谢谢你发布这篇文章-Sheets API文档对于如何执行简单操作(如this@ziganotschka$request->setRequests($body)代码>导致错误<代码>“消息”:“接收到无效的JSON负载。“请求”处的“未知名称\”valueInputOption \“找不到字段。\n接收到无效的JSON负载。“请求”处的“未知名称\”data \“找不到字段。”
。只有当我将它们分成两个调用时,它才能工作。更改值和添加行使用不同的URL,是否可以将它们合并<代码>邮政https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId/values:batchUpdatePOSThttps://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate