如何使用openpyxl知道Excel Python中的行跨度数

如何使用openpyxl知道Excel Python中的行跨度数,python,openpyxl,Python,Openpyxl,我想在python中使用openpyxl通过包含“abc”的第一列找到行跨度,即4。它不是一个特定的表,它在我的Excel工作表中的某个地方,我正在分析该工作表。一种方法是确定给定单元格是否在合并范围内 以下脚本将返回给定单元格的合并单元格的关联范围。它首先定位文本所在的单元格,然后尝试确定合并的单元格范围: import openpyxl def find_cell(ws, text): for row in ws.iter_rows(): for cell in


我想在python中使用openpyxl通过包含“abc”的第一列找到行跨度,即4。它不是一个特定的表,它在我的Excel工作表中的某个地方,我正在分析该工作表。

一种方法是确定给定单元格是否在合并范围内

以下脚本将返回给定单元格的合并单元格的关联范围。它首先定位文本所在的单元格,然后尝试确定合并的单元格范围:

import openpyxl

def find_cell(ws, text):
    for row in ws.iter_rows(): 
        for cell in row:
            if cell.value == text:
                return cell
    return None

def get_merged_range(ws, cell):
    if cell in ws.merged_cells:
        for merged_range in ws.merged_cell_ranges:
            if cell in [c[0] for c in openpyxl.utils.cells_from_range(merged_range)]:
                return merged_range
    return None

wb = openpyxl.load_workbook(filename = 'input.xlsx')
ws = wb.active

found_cell = find_cell(ws, 'abc').coordinate
print get_merged_range(ws, found_cell)

如果传递的单元格未合并,函数将返回
None

无需初始化单元格范围,如果单元格(坐标)未合并,则函数的其余部分将永远不会执行:
返回合并的单元格范围