代码之家  ›  专栏  ›  技术社区  ›  AFoeee

使用openpyxl和python3模拟Excel或LibreOffice Calc的复制功能(使用属性复制到新位置)

  •  0
  • AFoeee  · 技术社区  · 6 年前

    有没有办法模仿“Excel”或“LibreOffice Calc”的复制功能 openpyxl 还有蟒蛇3号?

    我想指定某个范围(例如“A1:E5”)并复制“边框”、“对齐”、“数字\u格式”、“值”、“合并的\u单元格”、。。。将每个单元格的属性设置到其他位置(可能是另一个工作表),由此使用的公式应自动更新到新位置。新公式旨在引用目标工作表中的单元格,而不是原始工作表中的旧单元格。


    我的项目:

    我每月生成一份工作簿。此工作簿包含列出所有工作日的产量监控表。 虽然每个月的表格都不同,但工作簿中的所有表格都具有相同的结构,因此我想创建一个模板并将其粘贴到各个工作表中。

    复制整个工作表并不是真正的解决方案,因为我还喜欢为每个工作表分别指定表的位置。因此,目标工作表中的位置可能与模板中的位置不同。


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

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

    顺致敬意, AFOEE公司

    2 回复  |  直到 6 年前
        1
  •  0
  •   Charlie Clark    6 年前

    openpyxl将允许您在工作簿中复制整个工作表。对于您的工作来说,这应该足够了,但如果您还需要,则需要编写自己的代码。

        2
  •  0
  •   AFoeee    6 年前

    由于openpyxl似乎并没有为我的问题提供一个通用的解决方案,因此我采取了以下步骤:

    我用单元格集的属性(边框、对齐、数字格式等)创建了一个模板。虽然公式是在相应的单元格中输入的,但列和行将替换为占位符。这些占位符表示到“零点”的偏移。

    如上所述复制模板区域,但在复制“cell.value”时,占位符用于计算目标工作表中的实际位置。

    顺致敬意,
    AFOEE公司