google-sheets-apigoogle-python-api

How to merge cells with Google Sheets API?


I am using the Python client for the Google Sheets API to build a spreadsheet. I am able to create a new sheet and update values in it, but I have been unable to merge cells for the header row that I want.

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()

This is the code I am running. There are no errors. The response's replies are empty and the spreadsheet doesn't have merged cells. The documentation is here.


Solution

  • Start indexes are inclusive and end indexes are exclusive, so by asking to merge row [0,1) you're saying "i want to merge row 0 into row 0", which is a no-op. You probably want [0,2), e.g:

    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
             }
        }}
    ]