简体   繁体   中英

Openpyxl - copy worksheet with merged cells

I'm trying to copy worksheets (within the same workbook) that have merged cells and I'm getting an error. I have fairly long templates that I copy and then populate for different projects. My code works if I unmerge all the cells, but that messes up all the formatting. I could unmerge the cells, copy the sheet, and then remerge them. However, there are a ton of merged cells and I have several different templates that I have to use. I don't have any control over the templates. I'm using openpyxl 2.5.4.

Here's my code:

wb = openpyxl.load_workbook(temp)
wb.save(filename = "test.xlsx")
pg = openpyxl.load_workbook("test.xlsx")
ws = pg.copy_worksheet(pg["sheet1"])

Here's the error:

Traceback (most recent call last):

  File "<ipython-input-41-a49f299a8c1f>", line 1, in <module>
    ws = pg.copy_worksheet(pg["sheet1"])

  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\workbook\workbook.py", line 394, in copy_worksheet
    cp.copy_worksheet()

  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\worksheet\copier.py", line 43, in copy_worksheet
    self.target.merged_cells = copy(self.source.merged_cells)

  File "C:\ProgramData\Anaconda3\lib\copy.py", line 88, in copy
    return copier(x)

  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\worksheet\cell_range.py", line 456, in __copy__
    n.ranges.append(copy(r))

  File "C:\ProgramData\Anaconda3\lib\copy.py", line 88, in copy
    return copier(x)

  File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\worksheet\cell_range.py", line 136, in __copy__
    title=self.title)

TypeError: __init__() got an unexpected keyword argument 'min_col'

I've seen other questions about copying styles for merged cells, but this won't copy the sheet at all. Any suggestions?

Thanks.

Brandon

You Can Easily Monkey Patch It:

from openpyxl.worksheet.merge import MergedCellRange

def clone(self):
    return self.__class__(self.ws, self.coord)

MergedCellRange.__copy__ = clone

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