简体   繁体   中英

Is there a way to copy merged cells using Python(openpyxl)?

I'm trying to make code using Python to repeatedly copy a certain range of Excel files.

Like the image file below, the same content is copied by placing a few columns on a sheet with existing content in the same sheet.

enter image description here

Despite being an introductory level of ability, at first I believed that it would be really easy to implement. And I have implemented the most of my plans through the code below except merged cells

import openpyxl
from openpyxl import Workbook
wb = openpyxl.load_workbook('DSD.xlsx')
ws = wb.worksheets[3]

from openpyxl.utils import range_boundaries
min_col, min_row, max_col, max_row = range_boundaries('I1')

for row, row_cells in enumerate(wb['2'], min_row):
    for column, cell in enumerate(row_cells, min_col):
        # Copy Value from Copy.Cell to given Worksheet.Cell
        ws.cell(row=row, column=column).value = cell.value
        ws.cell(row=row, column=column)._style = cell._style

wb.save('DSD.xlsx')

enter image description here

However, I've searching for a few days and thinking about it, but I don't know how to merge the merged cells. Beyond that, I don't even know if this is technically possible.

The way I thought of it today was to pull out a list of merged cells in the sheet and then add only more columns from the coordinates of each merged cell to add commands to merge to the same extent.

However, since I pulled out the list of merged cells as shown below, I can't think of what to do. Is there a way?

import openpyxl
from openpyxl import Workbook

wb=openpyxl.load_workbook('merged.xlsx')
ws=wb.active

Merged_Cells = ws.merged_cell_ranges

a = Merged_Cells[0]

print(ws.merged_cell_ranges)
print(a)
[<MergedCellRange B2:C3>, <MergedCellRange B9:C9>, <MergedCellRange B13:B14>]
B2:C3

The value B2:C3, corresponding to a, appears to be a special value in which a.replace(~~) does not work even if the value is seem to be "B2:C3".

Is there really no way?

You'll need to look at how CellRanges work because you will need to calculate the offset for each range and then create a new MergedCellRange for the new cell using the dimensions from the original.

The following should give you an idea of how to do ths.

from openpyxl.worksheet.cell_range import CellRange
area = CellRange("A1:F13") # area being copied

for mcr in ws.merged_cells:
    if mcr.coord not in area:
         continue
    cr = CellRange(mcr.coord)
    cr.shift(col_shift=10)
    ws.merge_cells(cr.coord)

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