使用Google表格API写入工作表

时间:2017-07-29 01:33:18

标签: php google-spreadsheet-api

我想把数据写入我的工作表:

$spreadsheetId = 'xxx';
$range = 'Test!A1:D5';

$values = [
  'range' => "A1",
  'majorDimension' => 'DIMENSION_UNSPECIFIED',
  'values' => [
    ["Item", "Cost", "Stocked", "Ship Date"],
    ["Wheel", "$20.50", "4", "3/1/2016"],
    ["Door", "$15", "2", "3/15/2016"],
    ["Engine", "$100", "1", "30/20/2016"],
  ],
];

$body = new Google_Service_Sheets_ValueRange(array(
  'values' => $values
));
$params = array(
  'valueInputOption' => 'RAW'
);
$result = $service->spreadsheets_values->update($spreadsheetId, $range, $body, $params);

但是在日志中我看到了:

PHP Fatal error:  Uncaught exception 'Google_Service_Exception' with message '{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"range\" at 'data.values': Cannot find field.\nInvalid JSON payload received. Unknown name \"major_dimension\" at 'data.values': Cannot find field.",
    "errors": [
      {
        "message": "Invalid JSON payload received. Unknown name \"range\" at 'data.values': Cannot find field.\nInvalid JSON payload received. Unknown name \"major_dimension\" at 'data.values': Cannot find field.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

我做错了什么?我将非常感谢适合您的示例代码:)

在示例中没有足够的信息(https://developers.google.com/sheets/api/guides/values#writing_to_a_single_range

3 个答案:

答案 0 :(得分:0)

你快到了。不要忘记包含工作表名称

 "range": "Sheet1!A1:D5"

检查Basic Writing guide以获取更多样本。

答案 1 :(得分:0)

试试这个:

$spreadsheetId = 'xxx';
$range = 'Test!A1:D5';

$values = [
    ["Item", "Cost", "Stocked", "Ship Date"],
    ["Wheel", "$20.50", "4", "3/1/2016"],
    ["Door", "$15", "2", "3/15/2016"],
    ["Engine", "$100", "1", "30/20/2016"],
];

$updateBody = new Google_Service_Sheets_ValueRange([
    'range' => $range,
    'majorDimension' => 'ROWS',
    'values' => $values,
]);

$valueInputOption = 'USER_ENTERED'; // Or RAW       

$params = [
  'valueInputOption' => $valueInputOption
];

$result = $this->sheetsService->spreadsheets_values->update(
    $spreadsheetID,
    $updateRange,
    $updateBody,
    $params
); 

答案 2 :(得分:0)

这里不是这种情况,但我通过从 NULL 数组内的项目中删除 values 值解决了类似的问题。

Google 的 PHP 库似乎很难解析这些值并最终生成无效的 JSON 负载。