GSpread Cell Merging

Question:

I am trying to merge cells in Gsheets using Gspread for Python, however I can’t find any documentation.

I have used the gspread_formatting module to format the text and colour of the cell, but I can’t find anything to do with merging of the cells.

I haven’t wrote any code because I can’t find any examples.

I want to be able to merge the cells based on a range.

Can anyone please help me?

Cheers.

Asked By: Dylan Logan

||

Answers:

  • You want to know how to merge cells of Google Spreadsheet using gspread.
  • You have already been able to put and get values to the Spreadsheet using gspread.

If my understanding is correct, how about this answer? In this modification, batch_update() method is used.

Sample script:

Please set spreadsheetId, sheetName and the gridrange of range.

spreadsheetId = "###"
sheetName = "Sheet1"

client = gspread.authorize(credentials)
ss = client.open_by_key(spreadsheetId)
sheetId = ss.worksheet(sheetName)._properties['sheetId']
body = {
    "requests": [
        {
            "mergeCells": {
                "mergeType": "MERGE_ALL",
                "range": {  # In this sample script, all cells of "A1:C3" of "Sheet1" are merged.
                    "sheetId": sheetId,
                    "startRowIndex": 0,
                    "endRowIndex": 3,
                    "startColumnIndex": 0,
                    "endColumnIndex": 3
                }
            }
        }
    ]
}
res = ss.batch_update(body)

Note:

  • Please set the range as the gridrange.
  • In this sample script, all cells of “A1:C3” of “Sheet1” are merged.
  • When MERGE_ALL is changed to MERGE_ROWS, the rows of “A1:C1”, “A2:C2” and “A3:C3” are merged.
  • When MERGE_ALL is changed to MERGE_COLUMNS, the columns of “A1:A3”, “B1:B3” and “C1:C3” are merged.

References:

If this was not useful for your situation, I apologize.

Answered By: Tanaike

Gspread now has documentation available for merging cells on this page.

If your worksheet’s name is my_ws and you wish to merge cells A1 to A5, you could enter the following:

my_ws.merge_cells(A1:A5, merge_type='MERGE_ALL')

Answered By: KBurchfiel