Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 316
ctp_9 Avatar asked Apr 19 '17 14:04

ctp_9


People also ask

How do I merge cells in Google Sheets API?

Merge cellsbatchUpdate request merges cells. The first request merges the A1:B2 range into a single cell. A second request merges the columns in A3:B6, while leaving the rows separated. The request protocol is shown below.

Can Google Sheets pull data from an API?

Once you've set up your API to Google Sheets connection, click Save And Run to get data to your spreadsheet.


1 Answers

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
         }
    }}
]
like image 137
Sam Berlin Avatar answered Sep 21 '22 06:09

Sam Berlin