Skip to main content
 首页 » 编程设计

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

2024年11月01日7lori

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(如上文所述)将数据从源工作表的 A 列第 2 行开始复制到目标工作表的 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”属性用于我自己的训练/学习目的。

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

这是我目前所拥有的:

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 并从第 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 之间的差距。提前致谢!

请您参考如下方法:

这将从 ws1 的行偏移 ws2 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")