import pandas as pd
from openpyxl import load_workbook
# 读取Excel文件
file_path = 'test.xlsx' # 替换为你的Excel文件路径
df = pd.read_excel(file_path)
# 显示读取的数据
print(df)
# 打开工作簿
wb = load_workbook(file_path)
ws = wb.active # 获取活动工作表
# 假设我们要合并的列是第1列(A列),从第二行开始(假设第一行为标题)
start_row = 2
last_row = ws.max_row
# 用于存储上一个唯一值以检测变化
previous_value = None
merge_start_row = None
# 遍历每一行
for row in range(start_row, last_row + 1):
current_value = ws[f'A{row}'].value # 第一列的值
# 检测当前值与上一个值
if current_value == previous_value:
# 如果值相同,继续合并
continue
else:
# 如果发现新的值,合并之前的单元格(如果有)
if merge_start_row is not None and row - merge_start_row > 1:
# 根据合并的行数分别合并其他列
for col in range(2, 8): # 从第2列到最后一列
ws.merge_cells(start_row=merge_start_row, start_column=col, end_row=row - 1, end_column=col)
# 更新为新值
previous_value = current_value
merge_start_row = row
# 最后合并最后一组相同的值(如果有)
if merge_start_row is not None and last_row - merge_start_row > 0:
for col in range(2, 8):
ws.merge_cells(start_row=merge_start_row, start_column=col, end_row=last_row, end_column=col)
# 保存合并后的文件
wb.save('merged_cells.xlsx') # 可以另存为新文件