首页 > 解决方案 > “if cell.value”比较相同的单元格但不执行

问题描述

我对openpyxl相当陌生,如果这是一个明显的错误,我深表歉意,但我已经要求其他人提供意见并且没有找到我的问题的根源。

我的目标是:

我为此目标编写的代码如下:

inputrow = 1  #row to copy from
outputrow = 1 #row to paste to

counter = 1

A = inputsheet.cell(row=inputrow,column=1).value #Write location name to A
B = inputsheet.cell(row=inputrow,column=2).value #Write application amount to B

while counter < 3: 
    
    #Iterate in OUTPUT for A
    for row in outputsheet.iter_rows():
        inputrow += 1                                             #moves onto next row from INPUT
        for cell in row:
            if cell.value == A:                                   #when find cell that matches A        
                print ('Found Cell matching A')
                outputsheet.cell(row=cell.row,column=2).value = B #Paste B into column adjacent to what was found
                print('Cycle successful')
                counter += 1
            
            else: #if the locations don't match
                print('Location not found within output, moving to next row')
                counter += 1
                
output.save('thispart.xlsm') #save finished file as copy

将此数据集用作“输入表”(输出表相同,只是缺少第 2 列中的数字):

|Stanton | |100|
|Hurston | |200|
|Crusader| |300|

我将其作为输出接收(以及以下控制台信息)

|Stanton | |100|
|Hurston | |   |
|Crusader| |   |

Found Cell matching A
Cycle successful
Found Cell matching A
Cycle successful
Location not found within output, moving to next row

我非常困惑,因为我的代码似乎在比较两个相同的值并认为它们是不同的。如果需要,可以随时获得其他信息。欢迎任何建议,谢谢!

标签: pythonexcelcellopenpyxl

解决方案


推荐阅读