Home > Mobile >  Getting coordinates of a certain merged cell
Getting coordinates of a certain merged cell

Time:09-20

I am trying to get starting and end column of a merged cell in excel - enter image description here

I am looking to know start and end column number of cell 'human readable'. This code gives me all merged cells in sheet -

from openpyxl import load_workbook
wb = load_workbook('Book2.xlsx')
sheet_ranges = wb['Sheet1']

print(sheet_ranges.merged_cells.ranges)

But how can I find only for 'human readable'?

CodePudding user response:

This worked out for me

from openpyxl import load_workbook

def main():
    wb = load_workbook("/Book2.xlsx")
    sheet = wb['Sheet1']
    cell = content_checker(sheet)
    merged_span_check(sheet, cell)

def content_checker(sheet):
    for row in sheet:
        for cell in row:
            if cell.value == 'Human Readable':
                return cell

def merged_span_check(sheet, cell):
    for merged_cell in sheet.merged_cells.ranges:
        if cell.coordinate in merged_cell:
            print(merged_cell)

if __name__ == '__main__':
    main()

CodePudding user response:

Should be able to use list comprehension to find and print all instances, includes check being case insensitive.

from openpyxl import load_workbook
wb = load_workbook('Book2.xlsx')
sheet_ranges = wb['Sheet1']

search = 'human readable'
newlist = [c for c in sheet_ranges.merged_cells.ranges
           if search in c.start_cell.internal_value.lower()]
print(newlist)
  • Related