簡體   English   中英

有沒有辦法使用 Python(openpyxl) 復制合並的單元格?

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

我正在嘗試使用 Python 編寫代碼以重復復制一定范圍的 Excel 文件。

像下面的圖像文件一樣,通過在工作表上放置幾列與同一工作表中的現有內容來復制相同的內容。

在此處輸入圖片說明

盡管是入門級的能力,但一開始我相信它真的很容易實現。 我已經通過下面的代碼實現了我的大部分計划,除了合並的單元格

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')

在此處輸入圖片說明

然而,我已經搜索了幾天並考慮了它,但我不知道如何合並合並的單元格。 除此之外,我什至不知道這在技術上是否可行。

我今天想到的方法是在sheet中拉出合並單元格的列表,然后從每個合並單元格的坐標中僅添加更多列,以添加合並到相同程度的命令。

但是,由於我拉出合並單元格的列表如下圖所示,我想不出該怎么做。 有辦法嗎?

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

對應於 a 的值 B2:C3 似乎是一個特殊值,其中 a.replace(~~) 不起作用,即使該值似乎是“B2:C3”。

真的沒有辦法嗎?

您需要查看 CellRanges 的工作方式,因為您需要計算每個范圍的偏移量,然后使用原始尺寸為新單元格創建一個新的 MergedCellRange。

以下應該讓您了解如何做到這一點。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM