pandas合并Excel单元格

-
-
2025-09-03 10:34
from openpyxl import load_workbook
from openpyxl.styles import Alignment

def merge_cell(file_path):
    """合并单元格"""
    wb = load_workbook(file_path)
    sheets = wb.sheetnames
    for single_sheet in sheets:
        ws = wb[single_sheet]
        # 获取第一列数据
        type_list = []
        i = 2
       total_row_num = worksheet.max_row
       while True:
           if i >= total_row_num:
               break
           type_list.append(r)
           i += 1

        # 判断合并单元格的始末位置
        s = 0
        e = 0
        flag = type_list[0]
        for i in range(len(type_list)):
            if type_list[i] != flag:
                flag = type_list[i]
                e = i - 1
                if e >= s:
                    ws.merge_cells("A" + str(s + 2) + ":A" + str(e + 2))
                    s = e + 1
            if i == len(type_list) - 1:
                e = i
                ws.merge_cells("A" + str(s + 2) + ":A" + str(e + 2))

        # 居中单元格
        ws_area = ws[f'A{2}:A{2 + len(type_list)}']
        for i in ws_area:
            for j in i:
                j.alignment = Alignment(horizontal='center', vertical='center')

    wb.save(file_path)

merge_cell('./output.xlsx')


清遥
遥夜泛清瑟,西风生翠萝。
微博热搜榜Top10

加载中...
最新评论

加载中...