使用 openpyxl 将一个工作表中的值附加到另一个工作表时输出不正确(但非常接近)

问题描述 投票:0回答:1

下面的代码片段非常接近创建正确的输出,但它缺少一些必需的行并添加了一些不应该的行,我不明白为什么。

LU = "Gilford"

for i, row in enumerate(sourcews2.iter_rows(min_row=5, min_col= 1, max_col=33)):
        if sourcews2.cell(row=i+1, column=1).value == LU:
            destinationws.append([cell.value for cell in row])

下图中的行(其中第一个单元格 = Gilford)是我尝试提取并附加到不同 Excel 工作表的行。

另一个Excel表格中的输出结果如下图所示。它缺少源工作表中 Gilford 堆栈顶部的 4 行,并且还添加了 Gilford 堆栈后面的 4 行(以“Gray”开头)。参考上面的代码片段,我不知道它如何或为什么会拉出以“Gray”开头的行。

python excel openpyxl
1个回答
0
投票

您无需担心自动追加。
您的代码可以工作,只是不需要额外的计数。
您所需要的只是以下内容;

from openpyxl import Workbook, load_workbook


sourcewb = load_workbook('data.xlsx')
sourcews2 = sourcewb['Sheet1']

destinationwb = Workbook()
destinationws = destinationwb.active

LU = "Gilford"

for row in sourcews2.iter_rows(min_row=5, min_col=1, max_col=33):
    if row[0].value == LU:
        destinationws.append([cell.value for cell in row])

destinationwb.save('new.xlsx')
© www.soinside.com 2019 - 2024. All rights reserved.