如何使用PHP中的Google表格API在一系列单元格上设置数据验证?

时间:2016-10-25 14:32:32

标签: php google-sheets-api

我有以下代码:

$requests = '{
  "requests": [
    {
      "setDataValidation": {
        "range": {
          "sheetId": mySheetID,
          "startRowIndex": 0,
          "endRowIndex": 10,
          "startColumnIndex": 0,
          "endColumnIndex": 6
        },
        "rule": {
          "condition": {
            "type": "NUMBER_GREATER",
            "values": [
              {
                "userEnteredValue": "5"
              }
            ]
          },
          "inputMessage": "Value must be > 5",
          "strict": true
        }
      }
    }
  ]
}';

// $client is a confirmed, working authorized Google_Client object.
$serviceSheets      = new \Google_Service_Sheets($client);
// NOTE This is not the same object as in \App\GoogleSheets
$batchUpdateRequest = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest;

$batchUpdateRequest->setRequests($requests);

$serviceSheets->spreadsheets->batchUpdate(
    // $id is correct.
    $id,
    $batchUpdateRequest
);

...我收到以下错误:

{
  "error": {
    "code": 400,
    "message": "Invalid value at 'requests' (type.googleapis.com/google.apps.sheets.v4.BatchUpdateSpreadsheetRequest.Request), \"{\n \"requests\": [\n {\n \"setDataValidation\": {\n \"range\": {\n \"sheetId\": \"1100288254\",\n \"startRowIndex\": 0,\n \"endRowIndex\": 10,\n \"startColumnIndex\": 0,\n \"endColumnIndex\": 6\n },\n \"rule\": {\n \"condition\": {\n \"type\": \"NUMBER_GREATER\",\n \"values\": [\n {\n \"userEnteredValue\": \"5\"\n }\n ]\n },\n \"inputMessage\": \"Value must be > 5\",\n \"strict\": true\n }\n }\n }\n ]\n}\"",
    "errors": [
      {
        "message": "Invalid value at 'requests' (type.googleapis.com/google.apps.sheets.v4.BatchUpdateSpreadsheetRequest.Request), \"{\n \"requests\": [\n {\n \"setDataValidation\": {\n \"range\": {\n \"sheetId\": \"1100288254\",\n \"startRowIndex\": 0,\n \"endRowIndex\": 10,\n \"startColumnIndex\": 0,\n \"endColumnIndex\": 6\n },\n \"rule\": {\n \"condition\": {\n \"type\": \"NUMBER_GREATER\",\n \"values\": [\n {\n \"userEnteredValue\": \"5\"\n }\n ]\n },\n \"inputMessage\": \"Value must be > 5\",\n \"strict\": true\n }\n }\n }\n ]\n}\"",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

我尝试将$requests作为数组传递,但它说它需要JSON,所以这不是问题。

我还尝试传递requests键(对象数组)和单setDataValidation个请求(对象)的值。

请求本身是从Google的docs复制的。

1 个答案:

答案 0 :(得分:0)

这是无效的JSON:

     "sheetId": mySheetIdConfirmedCorrect,
                              ^---- unquoted string

不要构建自己的JSON。构建一个普通的旧常规PHP数组结构,然后json_encode()它。

JSON也不能包含"代码",所以如果mySheet...实际上是一个变量,那么这又是无效的JSON。您不能传递除数据之外的任何内容 - 表达式,代码等...在JSON中都无效。