如何将单元格与Google表格API合并?

时间:2017-04-19 14:03:42

标签: google-sheets-api google-python-api

我正在使用Google表格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()

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

2 个答案:

答案 0 :(得分:3)

开始索引是包容性的,而结束索引是独占的,所以通过要求合并行[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
         }
    }}
]

答案 1 :(得分:0)

如果有人希望与PHP进行合并,则可以在下面使用以下代码:

首先要合并单元,您必须按照其文档(https://developers.google.com/sheets/api/quickstart/php)从composer下载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);