# 需要处理的文件
file = r'C:/Users/Administrator/Desktop/test/merge_res.xlsx'
wb = load_workbook(file)
# 数据存放的工作表'Sheet1'
ws = wb['Sheet1']
# 获取第一列数据
type_list = []
i = 2
while True:
r = ws.cell(i, 1).value
if r:
type_list.append(r)
else:
break
i += 1
# 判断合并单元格的始末位置
start = 0
end = 0
flag = type_list[0]
for i in range(len(type_list)):
if type_list[i] != flag:
flag = type_list[i]
end = i - 1
if end >= start:
ws.merge_cells("A" + str(start + 2) + ":A" + str(end + 2))
start = end + 1
if i == len(type_list) - 1:
end = i
ws.merge_cells("A" + str(start + 2) + ":A" + str(end + 2))
wb.save(file)
执行代码,返回文件打开merge_res.xlsx,需求完成!