【问题标题】:Is there a way to copy merged cells using Python(openpyxl)?有没有办法使用 Python(openpyxl)复制合并的单元格?
【发布时间】:2020-10-16 11:36:58
【问题描述】:

我正在尝试使用 Python 编写代码以重复复制一定范围的 Excel 文件。

像下面的图像文件一样,通过在一个工作表上放置几列与同一个工作表中的现有内容来复制相同的内容。

enter image description here

尽管是入门级的能力,起初我认为它真的很容易实现。我已经通过下面的代码实现了我的大部分计划,除了合并的单元格

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

但是,我已经搜索了几天并考虑了它,但我不知道如何合并合并的单元格。除此之外,我什至不知道这在技术上是否可行。

我今天想到的方法是在工作表中拉出一个合并单元格的列表,然后从每个合并单元格的坐标中仅添加更多列,以添加命令以合并到相同的程度。

但是,由于我拉出了如下所示的合并单元格列表,我想不出该怎么办。 有什么办法吗?

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”。

真的没有办法吗?

【问题讨论】:

    标签: python excel openpyxl


    【解决方案1】:

    您需要查看 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)
    

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多