Python Forum
How can I iterate through all cells in a column (with merge cells) with openpyxl?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I iterate through all cells in a column (with merge cells) with openpyxl?
#1
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!
Reply
#2
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
--
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python “Formula” Package: How do I parse Excel formula with a range of cells? JaneTan 1 708 Jul-12-2021, 11:09 AM
Last Post: jefsummers
  OpenPyxl: How to iterate through each Column (in 1 row) to find a value? chatguy 2 8,576 Apr-06-2021, 04:52 AM
Last Post: carlhyde
  Can you help me to merge the cells with OpenPyXL? TurboC 1 924 Feb-01-2021, 12:54 AM
Last Post: Larz60+
Question Python + Google Sheet | Best way to update specific cells in a single Update()? Vokofe 1 818 Dec-16-2020, 05:26 AM
Last Post: Vokofe
  Openpyxl tkinter search a value in Excel column Heathcliff_1 0 1,183 Dec-02-2020, 04:35 PM
Last Post: Heathcliff_1
  Python Openpyxl is unable to check from Column 6 onwards Skye 0 471 Oct-13-2020, 06:11 AM
Last Post: Skye
  How to merge three DataFrames based on specific column Mekala 0 743 Sep-08-2020, 02:01 PM
Last Post: Mekala
  identical cells in 2 different excel sheets python pandas esso 0 628 Jul-19-2020, 07:50 PM
Last Post: esso
  [openpyxl] Increment cells being pasted into Template Kristenl2784 4 1,457 Jul-16-2020, 10:00 PM
Last Post: Kristenl2784
  Copy certain cells into new workbook certain cells Kristenl2784 4 1,089 Jul-14-2020, 07:59 PM
Last Post: Kristenl2784

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020