问题
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.
回答1:
Try to follow the Insert an empty row or column guide. Indicate "ROWS" as your "dimension" and add how many rows you want by using startIndex and endIndex.
POST https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId:batchUpdate
{
"requests": [
{
"insertDimension": {
"range": {
"sheetId": sheetId,
"dimension": "ROWS",
"startIndex": 0,
"endIndex": 100
},
"inheritBefore": false
}
},
],
}
回答2:
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.
来源:https://stackoverflow.com/questions/42751757/add-multiple-rows-to-google-spreadsheet-via-api