简体   繁体   中英

Openpyxl - Merge same cells in column

I'm having trouble making a function that looks through a column (or each column) in the dataframe I'm writing and merging consecutive cells ie.

在此处输入图像描述

Would appreciate the help if anyone has done something like this. I've seen one response that uses pandas ExcelWriter, but don't think this is what I'm looking for.

This code will do the needful.

from openpyxl import load_workbook
file = "test.xlsx"
# Load workbook
wb = load_workbook(filename=file)
ws = wb['Sheet1']
mylist = []
for cell in ws['A']:
    mylist.append(cell.value)
mergecount=0
startcell=1
for row in range(1, len(mylist)):
    print(row, mylist[row-1], mylist[row])
    if mylist[row-1] == mylist[row]:
        mergecount += 1
    else:
        print(row, mylist[row-1], mylist[row], startcell, mergecount)
        if mergecount > 0:
            ws.merge_cells(start_row=startcell, start_column=1, end_row=startcell+mergecount, end_column=1)
        mergecount = 0
        startcell = row+1
if mergecount > 0:
    ws.merge_cells(start_row=startcell, start_column=1, end_row=startcell+mergecount, end_column=1)
wb.save(file)

Input and output sheets

输入工作表数据 输入工作表数据

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM