Python合并Excel相同连续单元格(已排序)

from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font

wb = load_workbook("C:/TEMP/test2.xlsx")
# ws = wb.active 选择工作簿
ws = wb[wb.sheetnames[0]]


# C/D/E列合并相同单元格
x1=None
x2=None
for i in range(1,ws.max_row+1):
    if x1 is None:
        tv=ws.cell(row=i, column=3).value
        x1=i
    if tv != ws.cell(row=i+1, column=3).value:
        x2=i
#         print(x1,x2)
    if x1 is not None and x2 is not None:
        ws['C{}'.format(x1)].alignment = Alignment(horizontal='center', vertical='center')
        ws.merge_cells('C{}:C{}'.format(x1,x2)) #合并单元格
        
        ws['D{}'.format(x1)].alignment = Alignment(horizontal='center', vertical='center')
        ws.merge_cells('D{}:D{}'.format(x1,x2)) #合并单元格
        
        ws['E{}'.format(x1)].alignment = Alignment(horizontal='center', vertical='center')
        ws.merge_cells('E{}:E{}'.format(x1,x2)) #合并单元格
        
        x1=None
        x2=None

    原文作者:繁梦溪
    原文地址: https://blog.csdn.net/FG24151110876/article/details/120346578
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞