如何使用PHP中的api v4从Google表格中删除行

时间:2018-02-02 02:35:46

标签: php google-api google-api-php-client google-sheets-api

我正在尝试使用Google为其API提供的Google API PHP客户端库删除Google表格中的一行。目前我只能清除行的内容但不能删除它:

 $requestBody = new Google_Service_Sheets_ClearValuesRequest();
 $range = 'Form responses 1!C5:H5';
 $response = $service->spreadsheets_values->clear($spreadsheetId, $range, $requestBody);

文档没有以任何方式解释如何删除除了提供与删除无关的一行HTTP,只有batchUpdate。

编辑:这是答案

$requests = [
  // Change the spreadsheet's title.
  new Google_Service_Sheets_Request([
    'deleteDimension' => [
      'range' => [
        'sheetId' => 'XXXXXXX', (THIS IS NOT THE SPREADSHEET ID - IT IS THE BIT AFTER GID IN THE URL)
        'dimension' => "ROWS",
        'startIndex' => '16',
        'endIndex' => '17'
      ]
    ]
])
]; 

2 个答案:

答案 0 :(得分:2)

您应该按照文档使用batchUpdate。

Delete rows or columns

以下spreadsheets.batchUpdate请求会删除工作表中的前三行。第二个请求删除列B:D。

请求协议如下所示。 Updating Spreadsheets指南介绍了如何使用Google API客户端库以不同语言实施批量更新。

POST https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate
{
  "requests": [
    {
      "deleteDimension": {
        "range": {
          "sheetId": sheetId,
          "dimension": "ROWS",
          "startIndex": 0,
          "endIndex": 3
        }
      }
    },
    {
      "deleteDimension": {
        "range": {
          "sheetId": sheetId,
          "dimension": "COLUMNS",
          "startIndex": 1,
          "endIndex": 4
        }
      }
    },
  ],
}

<?php
/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Google Sheets API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sheets
 * 2. Install the PHP client library with Composer. Check installation
 *    instructions at https://github.com/google/google-api-php-client.
 */

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

$client = getClient();

$service = new Google_Service_Sheets($client);

// The spreadsheet to apply the updates to.
$spreadsheetId = 'my-spreadsheet-id';  // TODO: Update placeholder value.

// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();

$response = $service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);

// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";

function getClient() {
  // TODO: Change placeholder below to generate authentication credentials. See
  // https://developers.google.com/sheets/quickstart/php#step_3_set_up_the_sample
  //
  // Authorize using one of the following scopes:
  //   'https://www.googleapis.com/auth/drive'
  //   'https://www.googleapis.com/auth/drive.file'
  //   'https://www.googleapis.com/auth/spreadsheets'
  return null;
}
?>

答案 1 :(得分:0)

最后,这段代码对我有用:

output