Python处理Excel坐标列表:按行合并生成对应单元格区间
实现方案
核心逻辑说明
我们需要先把每个Excel坐标拆分为列字母和行号,按行号分组后,取同一行最左和最右的坐标拼接为区间即可。为了兼容坐标乱序的场景,我们会把列字母转为数字做排序,保证区间首尾准确。
完整可运行代码
import re from openpyxl import load_workbook from openpyxl.utils import column_index_from_string # 坐标合并工具函数 def merge_coords(coords): row_groups = {} for coord in coords: # 拆分坐标的列字母和行号 match = re.match(r'([A-Z]+)(\d+)', coord) if not match: continue col_str, row_str = match.groups() row = int(row_str) # 列字母转数字,方便排序判断左右顺序 col_num = column_index_from_string(col_str) if row not in row_groups: row_groups[row] = [] row_groups[row].append((col_num, coord)) # 按行号升序生成区间结果 merged_result = [] for row in sorted(row_groups.keys()): # 同一行按列号从左到右排序 sorted_col_coords = sorted(row_groups[row], key=lambda x: x[0]) start_coord = sorted_col_coords[0][1] end_coord = sorted_col_coords[-1][1] merged_result.append(f"{start_coord}:{end_coord}") return merged_result # 原有坐标提取逻辑 + 合并处理 big_lst = [] merged_big_lst = [] # 最终存储所有sheet合并后的结果 wb = load_workbook("new_test.xlsx", data_only=True) for sheet_name in wb.sheetnames: ws = wb[sheet_name] small_lst = [] for row in ws: for cell in row: for i in range(10): if cell.value == f"DATA{i}": small_lst.append(cell.coordinate) big_lst.append(small_lst) # 直接对当前sheet的坐标做合并 merged_big_lst.append(merge_coords(small_lst)) # 测试打印结果 print(merged_big_lst)
效果验证
针对你给出的示例输入:
input_coords = [['A1', 'D1', 'G1', 'J1', 'V1', 'A3', 'D3', 'G3'], ['A1', 'D1', 'G1', 'J1', 'M1']]
调用merge_coords处理后输出结果为:
[["A1:V1","A3:G3"], ["A1:M1"]]
完全符合需求。
内容的提问来源于stack exchange,提问作者huhu
相关产品推荐
相关产品推荐

