python初学者,想用openpyxl实现每列相同单元格自动合并,未果,请问问题出在哪儿,谢谢

jfloapvg
  • 1
新手上路,请多包涵
mport openpyxl
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter, column_index_from_string
 
"""合并单元格"""
result_file = "E:\合并测试\合并1.xlsx"
wb = load_workbook(result_file)
ws = wb.get_sheet_by_name('Sheet1')
 
# 获取第一行数据
hang_list = []
j = 1
while True:
    l = ws.cell(1, j).value
    if l:
        hang_list.append(l)
    else:
        break
    j += 1


for j in range(len(hang_list)):
    print(j)
    type_list = []
    m=get_column_letter(j+1)
    flag=0
    print(m)
    # 获取第一列数据
    for i in range(2,len(type_list)):
        r = ws.cell(i, j+1).value
        if r:
            type_list.append(r)
        else:
            flag=1
            break
        i += 1  
    print(type_list)
    # 判断合并单元格的始末位置
    s = 0
    e = 0
    if flag==0:
        flag = type_list[0]
        print(flag)
        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(m+ str(s + 2) + ":"+m+ str(e + 2))
                    s = e + 1
                if i == len(type_list) - 1:
                    e = i
                    ws.merge_cells(m + str(s + 2) + ":"+m + str(e + 2))
    else:
        break
wb.save('合并.xlsx')
回复
阅读 355
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏