尝试使用 cell.offset 在源工作表和目标工作表具有不同起始行的工作表之间进行复制

Trying to use cell.offset to copy between worksheets where source and destination worksheets have different starting rows

openpyxl 具有带 属性 偏移量的单元模块: https://openpyxl.readthedocs.io/en/stable/api/openpyxl.cell.cell.html

offset(row=0, column=0)[source]
Returns a cell location relative to this cell.

Parameters: 
row (int) – number of rows to offset
column (int) – number of columns to offset
Return type:    
openpyxl.cell.Cell

我正在尝试了解如何使用 cell.offset(如上文所述)从源作品sheet 复制数据,从 A 列第 2 行开始到目标 sheet 开始在 A 列的第 7 行。

我实际上可以通过以下不同的方法实现这一点:

row_offset=5
for rows in ws2.iter_rows(min_row=2, max_row=None, min_col=1, max_col=1):
    for cell in rows:
        ws3.cell(row=cell.row + row_offset, column=1, value=cell.value)
        wb3.save('C:\folder\destOutputOffsetby5.xlsx')

以上将数据从 ws2 从第 2 行开始复制到 ws3 从第 7 行开始(由于偏移量为 5)。

但我想使用 'cell' 模块 'offset' 属性 用于我自己的 training/learning 目的。

如何用偏移模块替换上面的内容?

这是我目前的情况:

for row in ws2.iter_rows(min_row=2, max_row=None, min_col=1, max_col=1):    
    for cell in row:
        foo = cell.offset(row=5, column=0)

如果我那么运行:

"print(foo)"

我得到正确的偏移起始行加上附加行(此处未显示):

<Cell 'report1570826222449'.A7>
<Cell 'report1570826222449'.A8>
<Cell 'report1570826222449'.A9>

等等。

如果我 运行

print(foo.value)

我当然得到数据本身:

2019-10-03 00:00:00
2019-10-02 00:00:00

等等。

但我想不出将 foo(或 foo.value?)从 ws2 复制到 ws3。我尝试的每一种方法都简单地忽略 cell.offset 并写入目标工作 sheet 从第 2 行而不是第 7 行开始的列 A。

ws3 是:

wb3 = load_workbook('C:\folder\DetOutPutOffset5.xlsx')
ws3 = wb3['Sheet2']

这不会复制任何数据,因为 ws3 中没有真正改变任何内容。

for rows in ws2.iter_rows(min_row=2, max_row=None, min_col=1, max_col=1):
    for cell in rows:
        cell.offset(row=5, column=0)
        wb3.save('C:\folder\Destfile.xlsx')

还有这个:

for rows in ws2.iter_rows(min_row=2, max_row=None, min_col=1, max_col=1):
    for cell in rows:
        ws3.cell.offset(row=5, column=0)
        wb3.save('C:\folder\Destfile.xlsx')

抛出异常

AttributeError: 'function' object has no attribute 'offset'

有什么建议吗?我觉得我在这里只是缺少一些基本概念来弥合 ws2 和 ws3 之间的差距。提前致谢!

这会将 ws2 上的值从 ws1 的行偏移 5 行:

from openpyxl import load_workbook

wb = load_workbook("copies.xlsx")
ws1 = wb.worksheets[0]
ws2 = wb.worksheets[1]

# Get the row
for rows in ws1.iter_rows(min_row=2, max_row=None, min_col=1, max_col=1):
    # Get the cell
    for cell in rows:
        # offset the values for cells on ws2 with cell offset
        ws2.cell(row=cell.offset(row=5, column=0).row, column=1, value=cell.value)
wb.save("copies_copied.xlsx")