Python Forum

Full Version: How can I iterate through all cells in a column (with merge cells) with openpyxl?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have to write data in an excel sheet that contains merged cells, but I don't know how to do it because I can't identify the merged cells. For example, if I read all the cells in the first column of the sheet shown below, I read all of them, even if some of them belong to some merged cells:

>>> wb = openpyxl.load_workbook('test.xlsx')
>>> ws = wb['TEST']
>>>
>>> for cell in ws["A"]:
...     print(cell.value)
...
None
None
None
None
>>>
[Image: 8a2ac11369689167]

Here I can read four cells, but all of them are merged! I need to identify the main one not all of them. How can I iterate through all the "right" cells in a column? I have to identify the merged cells and write on them!
I made an excel sheet with three merged cells to match your image. Try this:
>>> from openpyxl.cell import MergedCell
>>> for cell in ws["A"]:
...   print(cell)
...   print(cell.value)
...   print(isinstance(cell, MergedCell))
...   print('--')
...
<Cell 'Sheet1'.A1>
None
False
--
<MergedCell 'Sheet1'.A2>
None
True
--
<MergedCell 'Sheet1'.A3>
None
True
--