【问题标题】:PHP - Google API Copy and Paste row keeping the original formatPHP - 保留原始格式的 Google API 复制和粘贴行
【发布时间】:2021-04-14 00:24:49
【问题描述】:

我有 2 个谷歌电子表格文档,MainSpreadsheet 和 SecondarySpreadSheet。 MainSpreadsheet 有很多行,其中一些我需要复制并保留样式格式。所以我需要从 MainSpreadSheet 中取出一些特定的行,然后使用 Google API PHP 将它们粘贴到 SecondarySpreadSheet 中。我正在尝试使用类名 Google_Service_Sheets_CopyPasteRequest() 但我无法解决问题。你们能帮我复制和粘贴与 MainSpreadsheet 相同的格式样式吗? 感谢你们的时间。

$newSpreadSheetID = '12345' ;

$mainSpreadSheetID = '54321';


$client = new \Google_Client();
$client->setApplicationName('NAME');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig('credentials.json');
$service = new Google_Service_Sheets($client);


/**
 * Copy from the Main Sheet
 */
$mainFirstSheetID = null;
$worksheetSheets = $service->spreadsheets->get($mainSpreadSheetID)->sheets;
foreach($worksheetSheets as $sheet){
    $mainFirstSheetID = $sheet->properties['sheetId'];     
}


$copyRange = new Google_Service_Sheets_GridRange();
$copyRange->setSheetId($mainFirstSheetID);
$copyRange->setStartRowIndex(10);
$copyRange->setEndRowIndex(11);
$copyRange->setStartColumnIndex(0);
$copyRange->setEndColumnIndex(400);

/**
 * Paste in the new SHEET
 */
$newSheetID = null;
$worksheetSheets = $service->spreadsheets->get($newSpreadSheetID)->sheets;
foreach($worksheetSheets as $sheet){ 
    $newSheetID = $sheet->properties['sheetId'];     
}

$pasteRange = new Google_Service_Sheets_GridRange();
$pasteRange->setSheetId($newSheetID);
$pasteRange->setStartRowIndex(10);
$pasteRange->setEndRowIndex(11);
$pasteRange->setStartColumnIndex(0);
$pasteRange->setEndColumnIndex(400);


$copypasteRequest = new Google_Service_Sheets_CopyPasteRequest();

$copypasteRequest->setSource($copyRange);
$copypasteRequest->setDestination($pasteRange);


$request = new Google_Service_Sheets_Request(); 
$request->setCopyPaste($copypasteRequest);

$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$batchUpdateRequest->setRequests($request);

$newSpreadsheet = $service->spreadsheets->get($newSpreadSheetID);

$mainSpreadsheet = $service->spreadsheets->get($mainSpreadSheetID);

$finalRowRange = $newSpreadsheet->range;
$finalRowStartPosition = strpos($newSpreadsheet->range,':') + 2;
$finalRow = intval(substr($finalRowRange,$finalRowStartPosition));

if($finalRow <= $pasteRange['startRowIndex']){
    $appendDimensionRequest = new Google_Service_Sheets_AppendDimensionRequest();
    $appendDimensionRequest->setSheetId($newSheetID);
    $appendDimensionRequest->setDimension("ROWS");
    $appendDimensionRequest->setLength(1);
    $appendRequest = new Google_Service_Sheets_Request(); 
    $appendRequest->setAppendDimension($appendDimensionRequest);
    $appendEmptyRowBatchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
    $appendEmptyRowBatchUpdateRequest->setRequests($appendRequest);
    $service->spreadsheets->batchUpdate($newSpreadSheetID, $appendEmptyRowBatchUpdateRequest);
}
$service->spreadsheets->batchUpdate($newSpreadSheetID, $batchUpdateRequest);


$service->spreadsheets_values->update(
    $newSpreadSheetID,
    $finalRow,
    $copypasteRequest
);

【问题讨论】:

  • 你能展示你当前的脚本吗?而且,不幸的是,来自So I need to take some specific rows from the MainSpreadSheet and paste them in the SecondarySpreadSheet using Google API PHP.,我无法理解您目标的细节。我为此道歉。另外,您能否提供您期望的示例输入和输出情况?
  • 我正在使用与此类似的代码。但这对我不起作用。 =>stackoverflow.com/questions/59212745/…
  • 感谢您的回复。来自I was using the code similar to this one.,关于您当前的脚本,您可以将其添加到您的问题中吗?而且,我必须为我糟糕的英语水平道歉。不幸的是,从您的回复中,来自So I need to take some specific rows from the MainSpreadSheet and paste them in the SecondarySpreadSheet using Google API PHP.,我仍然无法理解您目标的细节。我为此道歉。另外,您能否提供您期望的示例输入和输出情况?
  • 完成,谢谢。你能理解我是如何试图从代码中删除 $this-> 的吗?
  • 感谢您回复并添加更多信息。我可以确认您的 2 个样本电子表格。在您的目标中,您希望从“MAIN SHEET”的电子表格中检索特定行,并希望将该行复制到“NEW SHEET”电子表格的第一个空行。我的理解正确吗?如果我的理解是正确的,在您的实际情况下,您会从“MAIN SHEET”中检索多行吗?或者,您希望每次运行只检索一行?

标签: php google-sheets google-sheets-formula google-sheets-api google-api-php-client


【解决方案1】:

我相信你的目标和你目前的情况如下。

  • 您想将“MAIN SHEET”电子表格的一行复制到“NEW SHEET”电子表格的第一个空行。
  • 您不仅要复制值,还要复制单元格格式。
  • 您希望使用 googleapis for PHP 来实现此目的。
  • 您已经能够使用 Sheets API 为 Google 电子表格获取和输入值。

修改点:

  • 很遗憾,batchUpdate 方法的“CopyPasteRequest”无法从 Google 电子表格复制到其他 Google 电子表格。看来这是目前的规范。

  • 为了不仅将值,而且将单元格​​格式从谷歌电子表格“MAIN SHEET”复制到谷歌电子表格“NEW SHEET”,我想提出以下流程。

    1. 将源电子表格中的源工作表复制到目标电子表格。
    2. 检索目标工作表的第一个空行号。
    3. 将具有格式的值从复制的工作表复制到目标工作表。并且,删除复制的工作表。

此流来自my recent answer。但这是python脚本。因此,为了将此流程用于 PHP,我回答了一个示例脚本。当以上几点反映到脚本中时,它变成如下。

示例脚本:

在此示例脚本中,使用了您的 $service。所以请添加授权脚本。并且,请设置运行脚本的变量。

$service = new Google_Service_Sheets($client); // <--- This is from your script.

$copiedRowNumber = 16; // Please set the row number of "MAIN SHEET" that you want to copy.
$sourceSpreadsheetId = "###"; // Please set the source Spreadsheet ID.
$sourceSheetId = "0"; // Please set the source sheet ID.
$destinationSpreadsheetId = "###"; // Please set the destination Spreadsheet ID.
$destinationSheetName = "Página1"; // Please set the destination sheet name.
$destinationSheetId = "0"; // Please set the destination sheet ID.

// 1. Copy the source sheet in the source Spreadsheet to the destination Spreadsheet.
$requestBody = new Google_Service_Sheets_CopySheetToAnotherSpreadsheetRequest(
    array("destinationSpreadsheetId" => $destinationSpreadsheetId)
);
$res1 = $service->spreadsheets_sheets->copyTo($sourceSpreadsheetId, $sourceSheetId, $requestBody);
$copiedSheetId = $res1["sheetId"];

// 2. Retrieve 1st empty row number of the destination sheet.
$res2 = $service->spreadsheets_values->get($destinationSpreadsheetId, $destinationSheetName);
$row = count($res2["values"]);

// 3. Copy the values with the format from the copied sheet to the destination sheet. And, delete the copied sheet.
$requests = [
    new \Google_Service_Sheets_Request([
        'copyPaste' => [
            'source' => [
                'sheetId' => $copiedSheetId,
                'startRowIndex' => $copiedRowNumber - 1,
                'endRowIndex' => $copiedRowNumber,
            ],
            'destination' => [
                'sheetId' => $destinationSheetId,
                'startRowIndex' => $row,
                'endRowIndex' => $row + 1
            ],
            'pasteType' => 'PASTE_NORMAL',
        ],
    ]),
    new \Google_Service_Sheets_Request([
        'deleteSheet' => ['sheetId' => $copiedSheetId]
    ])
];
$batchUpdateRequest = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest(['requests' => $requests]);
$res3 = $service->spreadsheets->batchUpdate($destinationSpreadsheetId, $batchUpdateRequest);

注意:

  • 在此示例脚本中,假设您的$service = new Google_Service_Sheets($client); 可用于使用上述脚本。请注意这一点。

参考资料:

【讨论】:

  • 我认为只有一件事会更好。如果工作表上没有行,则带有$res2["values"] 的行将不存在,因此不会设置 $row 并给出错误。添加if(isset($res2["values"])){$row = count($res2["values"]);}else{$row = 0;} 即可解决问题。
  • @Hygison Brandao 感谢您提供更多信息。
猜你喜欢
  • 1970-01-01
  • 2010-12-30
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 2016-02-20
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多