简体   繁体   English

Openpyxl - 合并列中的相同单元格

[英]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.我在制作 function 时遇到问题,它查看 dataframe 中的一列(或每一列)我正在编写和合并连续的单元格,即。

在此处输入图像描述

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.我见过一个使用 pandas ExcelWriter 的响应,但不要认为这就是我要找的。

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输入和output张

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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