6

我正在使用用于 Google Sheets API 的 Python 客户端来构建电子表格。我能够创建一个新工作表并更新其中的值,但我无法合并我想要的标题行的单元格。

top_header_format = [
    {'mergeCells': {
        'mergeType': 'MERGE_COLUMNS',
        'range': {
            'endColumnIndex': 3,
            'endRowIndex': 1,
            'sheetId': '112501875',
            'startColumnIndex': 0,
            'startRowIndex': 0
        }
    }},
    {'mergeCells': {
        'mergeType': 'MERGE_COLUMNS',
         'range': {
             'endColumnIndex': 5,
             'endRowIndex': 1,
             'sheetId': '112501875',
             'startColumnIndex': 3,
             'startRowIndex': 0
         }
    }}
]

service.spreadsheets().batchUpdate(
    spreadsheetId=spreadsheet_id,
    body={'requests': top_header_format}
).execute()

这是我正在运行的代码。没有错误。响应的回复是空的,并且电子表格没有合并的单元格。文档在这里

4

2 回答 2

7

起始索引是包容性的,而结束索引是排斥性的,因此通过要求合并行 [0,1),您是在说“我想将第 0 行合并到第 0 行”,这是一个无操作。您可能想要 [0,2),例如:

top_header_format = [
    {'mergeCells': {
        'mergeType': 'MERGE_COLUMNS',
        'range': {
            'endColumnIndex': 4,
            'endRowIndex': 2,
            'sheetId': '112501875',
            'startColumnIndex': 0,
            'startRowIndex': 0
        }
    }},
    {'mergeCells': {
        'mergeType': 'MERGE_COLUMNS',
         'range': {
             'endColumnIndex': 6,
             'endRowIndex': 2,
             'sheetId': '112501875',
             'startColumnIndex': 3,
             'startRowIndex': 0
         }
    }}
]
于 2017-04-19T17:03:47.200 回答
1

如果有人想与 PHP 合并,您可以使用以下代码:

要首先合并单元格,您必须从 composer 下载 PHP 库,如其文档(https://developers.google.com/sheets/api/quickstart/php)中所述,一旦安装,请按照他们的指南设置您的客户端以获得身份验证.

    //$client will be your Google_Client authentication, for more info check the documentation link above.

使用下面的代码来合并行和列

    $service = new Google_Service_Sheets($client);

    $spreadsheetId = '1jfUz2VMUUEt2s4BP2Ye';    //this is test spreadsheet it, use your spreadsheet id here

    $rangeinst = new Google_Service_Sheets_GridRange();
    $rangeinst->setSheetId(0);  //your sheet id
    $rangeinst->setStartRowIndex(1);    // row index from where to start
    $rangeinst->setEndRowIndex(11); //ending row upto which you want merging
    $rangeinst->setStartColumnIndex(0); //start of column index, first column has 0 index like row
    $rangeinst->setEndColumnIndex(4);   //end of column upto which you want merging
    $merge = new Google_Service_Sheets_MergeCellsRequest();
    $merge->setMergeType('MERGE_COLUMNS');  //merge type request
    $merge->setRange($rangeinst);

    $requestBody = new Google_Service_Sheets_Request();
    $requestBody->setMergeCells($merge);
    $requestBatchBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
    $requestBatchBody->setRequests($requestBody);


    $response = $service->spreadsheets->batchUpdate($spreadsheetId, $requestBatchBody);
    echo "<pre>";
    print_r($response);
于 2019-01-03T10:26:25.987 回答