1 回答
TA贡献1824条经验 获得超6个赞
我通常不会回答我自己的问题,但鉴于 Google 将于 2020 年 3 月关闭 v3 Sheets API,我怀疑其他人可能会遇到这个问题。
正如我在对原始问题的评论中提到的那样,v4 API 中没有访问单元格格式的现有方法。因此,没有选项可以遍历一个范围并将格式应用于另一个范围。
我的解决方案是复制/粘贴前一行(默认 PASTE_NORMAL 将复制所有值、公式、格式并合并https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request# pastetype ) 然后用所需的值覆盖新粘贴的行。这为我提供了新行中现有格式所需的值:-
$sheetId = null;
$worksheetSheets = $this->spreadsheetService->spreadsheets->get($this->spreadsheetId)->sheets;
foreach($worksheetSheets as $sheet){
$sheetTitle = $sheet->properties['title'];
if ($sheetTitle === $this->worksheetTitle){
$sheetId = $sheet->properties['sheetId'];
break;
}
}
$copyRange = new Google_Service_Sheets_GridRange();
$copyRange->setSheetId($sheetId);
$copyRange->setStartRowIndex($nextRow - 2);
$copyRange->setEndRowIndex($nextRow - 1);
$copyRange->setStartColumnIndex(0);
$copyRange->setEndColumnIndex(400);
$pasteRange = new Google_Service_Sheets_GridRange();
$pasteRange->setSheetId($sheetId);
$pasteRange->setStartRowIndex($nextRow - 1);
$pasteRange->setEndRowIndex($nextRow);
$pasteRange->setStartColumnIndex(0);
$pasteRange->setEndColumnIndex(400);
$copypasteRequest = new Google_Service_Sheets_CopyPasteRequest();
$copypasteRequest->setSource($copyRange);
$copypasteRequest->setDestination($pasteRange);
//$copypasteRequest->pasteType(CopyPasteType.PASTE_NORMAL);
$request = new Google_Service_Sheets_Request();
$request-> setCopyPaste($copypasteRequest);
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$batchUpdateRequest->setRequests($request);
// Need to check if sheet has an existing empty row to paste into
$finalRowRange = $this->worksheet['range'];
$finalRowStartPosition = strpos($this->worksheet['range'],':') + 2;
$finalRow = intval(substr($finalRowRange,$finalRowStartPosition));
if($finalRow <= $pasteRange['startRowIndex']){ // startRowIndex is a zero based array range, i.e. 348 actually corresponds to row 349 on sheet.
$appendDimensionRequest = new Google_Service_Sheets_AppendDimensionRequest();
$appendDimensionRequest->setSheetId($sheetId);
$appendDimensionRequest->setDimension("ROWS");
$appendDimensionRequest->setLength(1);
$appendRequest = new Google_Service_Sheets_Request();
$appendRequest->setAppendDimension($appendDimensionRequest);
$appendEmptyRowBatchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$appendEmptyRowBatchUpdateRequest->setRequests($appendRequest);
$this->spreadsheetService->spreadsheets->batchUpdate($this->spreadsheetId, $appendEmptyRowBatchUpdateRequest);
}
$this->spreadsheetService->spreadsheets->batchUpdate($this->spreadsheetId, $batchUpdateRequest);
// The actual data values insert
$this->spreadsheetService->spreadsheets_values->update(
$this->spreadsheetId,
$updateRange,
$valueRange,
$conf
);
我希望这可能对将来的某些人有用。
- 1 回答
- 0 关注
- 73 浏览
添加回答
举报