Skip to content
Advertisement

Get combined/merged cells value

I’m coding a new python script that need to extract data from google sheets, but there are many cells which are merged/combined, and only the top-left cell from this merge has the value. It’s important to have that value on all the merged cells.

How can I do that?

Python 3.8.5 + gspread 3.6.0

Note: every comment “trying to get…”, the code right below it should return the same value as the previous code.

Spreadsheet test: https://docs.google.com/spreadsheets/d/17Dyxufu1y1ouBCPkf5Y7Vt1UW70WroK0Moy_DD7bZKc/edit?usp=sharing

Code for reproducing the problem:

JavaScript

The output is like this:

JavaScript

The point is: A2 must be equals to A1… E2=D2, D7==D6… But it seems there’s no way of handling merged cells with gspread.

Advertisement

Answer

I believe your goal as follows.

  • You want to retrieve the values from the merged cells using gspread of python.

In your sample Spreadsheet, for example, the cells “A1:L12” are merged. Under this condition, when the values are retrieved from the merged cells of “A1:L12” using Sheets API, just to confirm, the value "row_merged" has been put to cell D2 originally. Value "col_merged" is in D6 initially. Since it's merged, the expected result should be found on all merged cells is retrieved only cell “A1”. So in order to retrieve the same values from all cells of “A1:L12”, it is required to put the values to the cells “A2:L12”. Unfortunately, it seems that there are no methods for directly achieving this situation in Sheets API. So, in this answer, I would like to propose this using a script.

By the way, about result = ws.acell('A2') in your script, this cell is not merged and it’s empty. So in this case, I think that the empty value is correct. I thought that you might have wanted to check the cell “B1”. In this answer, this is also considered.

Sample script:

JavaScript

Note:

  • In this sample script, the method of “spreadsheets.get” in Sheets API is used with requests using the access token retrieved from client = gspread.authorize(credentials) of gspread.
  • In this sample script, the values are processed in the list. So when you retrieved the values from the merged cells, please retrieve them from the list values.

Reference:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement