用openpyxl和python3模仿Excel或LibreOffice Calc的复制功能(copy with properties to new position)

Imitate the copy function of Excel or LibreOffice Calc with openpyxl and python3 (copy with properties to new position)

有没有办法用openpyxl和python3模仿"Excel"或"LibreOffice Calc"的复制功能?

我想指定一个范围(例如"A1:E5")并复制"border"、"alignment"、"number_format"、"value"、"merged_cells", ... 每个单元格的属性到另一个位置(并且可能到另一个工作sheet),由此使用的公式应该自动更新到新位置。新公式旨在引用目标作品sheet 中的单元格,而不是原始作品sheet 中的旧单元格。


我的项目:

我每个月都会生成一个工作簿。此工作簿包含列出所有工作日的产量监控 table。 虽然 table 每个月都不同,但在工作簿中都具有相同的结构,所以我想创建一个模板并将其粘贴到个人作品 sheet 中。

复制整个作品sheet并不是真正的解决方案,因为我也喜欢为每个作品sheet单独指定table的位置。因此目标 sheet 中的位置可能与模板中的位置不同。


我当前的代码(其中的公式不会自动更新):

import copy

# The tuple "topLeftCell" represents the assumed new position in the target worksheet. It is zero-based. (e.g. (0,0) or (7,3))
# "templateSheet" is the template from which to copy.
# "worksheet" is the target worksheet

# Create the same "merged_cells" as in the template at the new positioin
for cell_range in templateSheet.merged_cells.ranges:
    startCol, startRow, endCol, endRow = cell_range.bounds
    worksheet.merge_cells(start_column=topLeftCell[0] + startCol,
                           start_row=topLeftCell[1] + startRow,
                           end_column=topLeftCell[0] + endCol,
                           end_row=topLeftCell[1] + endRow)

colNumber = topLeftCell[0] + 1         # 1 is added up because topLeftCell is zero based.
rowNumber = topLeftCell[1] + 1         # 1 is added up because topLeftcell is zero based.

# Copy the properties of the old cells into the target worksheet
for row in templateSheet[templateSheet.dimensions]:
    tmpCol = colNumber                 # sets the column back to the original value
    for cell in row:
        ws_cell = worksheet.cell(column=tmpCol, row=rowNumber)

        ws_cell.alignment = copy.copy(cell.alignment)
        ws_cell.border = copy.copy(cell.border)
        ws_cell.font = copy.copy(cell.font)
        ws_cell.number_format = copy.copy(cell.number_format)
        ws_cell.value = cell.value

        tmpCol += 1                    # move one column further
    rowNumber += 1                     # moves to the next line



由于复制范围实际上是一项常见任务,因此我假设 openpyxl 提供了执行此操作的函数或方法。不幸的是,到目前为止我找不到。
我正在使用 openpyxl 版本 2.5.1(和 Python 3.5.2)。

此致 阿福

openpyxl 可让您复制工作簿中的整个工作表。这对您的工作应该足够了,但如果您需要更多,您将需要编写自己的代码。

由于openpyxl似乎没有为我的问题提供通用的解决方案,所以我进行了以下操作:

我创建了一个模板,其中设置了单元格的属性(边框、对齐方式、数字格式等)。虽然公式输入到相应的单元格中,但列和行被占位符替换。这些占位符表示 "zero point".

的偏移量

模板区域按上述方法复制,但复制时"cell.value",占位符用于计算目标工作表中的实际位置

此致
阿福