Skip to content
Advertisement

Write to Sheet with Google Sheets API

I want write data to my sheet:

$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);

But in log i see:

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"
  }
}

What am I doing wrong? I will be grateful for the example code that works for you 🙂

In the examples there is not enough information( https://developers.google.com/sheets/api/guides/values#writing_to_a_single_range)

Advertisement

Answer

You’re almost there. Don’t forget to include the sheet name

 "range": "Sheet1!A1:D5"

Check the Basic Writing guide for more samples.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement