Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple rows to Google Spreadsheet via API

I can add a new row to a Google spreadsheet with this code:

$valueRange = new Google_Service_Sheets_ValueRange();
$valueRange->setValues(["values" => ['data1', 'data2']]);
$range = 'Sheet1!A1:A';
$conf = ["valueInputOption" => "USER_ENTERED"];
$service->spreadsheets_values->append($spreadsheetId, $range, $valueRange, $conf);

How should I change the setValues params to add multiple rows?

Thank you.

UPDATE

In the meantime I use this approach:

$range_number = 1; // Keep spreadsheet header
$data = array();
for($i=0;$i<count($data);$i++){
    $range_number++;
    $range = 'Sheet1!A'.$range_number.':XX';
    $values = array( array($data1[$i], $data2[$i], $data3[$i]) );
    $data[] = new Google_Service_Sheets_ValueRange(
        array( 'range' => $range, 'values' => $values )
    );
}
$body = new Google_Service_Sheets_BatchUpdateValuesRequest(array(
  'valueInputOption' => "USER_ENTERED",
  'data' => $data
));
$result = $service->spreadsheets_values->batchUpdate($spreadsheetId, $body);

// Clear rest of spreadsheet
$range_number++;
$range = 'Sheet1!A'.$range_number.':XX';
$clearRange = new Google_Service_Sheets_ClearValuesRequest();
$service->spreadsheets_values->clear($spreadsheetId, $range, $clearRange);

But this way I have to send the previous data as well. My goal would be just to append the new data.

like image 784
Zoltan Avatar asked Mar 12 '17 19:03

Zoltan


People also ask

Can you insert more than one row at a time in Google Sheets?

In Google Sheets, adding a row one at a time can get repetitive. With the right-click drop down menu, you are able to add multiple rows at once.


1 Answers

For those of you who want to append multiple rows instead of update rows. You can use this solution.

$valueRange = new Google_Service_Sheets_ValueRange();

$valueRange->setValues([['John', 'Doe'],['Jane', 'Doe']]);

$range = 'Sheet1!A1:A';
$conf = ["valueInputOption" => "USER_ENTERED"];
$service->spreadsheets_values->append($spreadsheetId, $range, $valueRange, $conf);

It took me ages to work this out hope it helps.

like image 197
RyDog Avatar answered Sep 20 '22 21:09

RyDog