答案 0 :(得分:1)
一种方法是确定给定单元格是否在合并范围内。
以下脚本将返回给定单元格的关联合并单元格范围。首先,它找到文本所在的单元格,然后尝试确定合并的单元格范围:
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
。