使用openpyxl移动到相邻的单元格 [英] Move to adjacent cells using openpyxl

查看:209
本文介绍了使用openpyxl移动到相邻的单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种算法,可以在单元格中找到一个值,在这种情况下,可以说单元格为C10.我需要在D列中的该值旁边查找一个值,如果该值与我需要的值不匹配,则从该值上移一个单元格并检查是否匹配,等等.到目前为止,我已经做到这一点:

I have an algorithm that finds a value in a cell, for this case lets say that cell is C10. I need to look next to that in column D for a value, and if that value doesnt match what i need, to go up one cell from that and check for a match, etc. I have this so far:

bits = [] 

for row in ws.iter_rows(row_offset=4,column_offset=3):
    #skip over empty rows
    if row:
        #current cell is in column C
        cell = row[2]
        try:
            #find the lowest address in the excel sheet
            if cell.internal_value == min(address):
                #somehow match up in column d
                for '''loop and search col D''':
                    if str(row[3].internal_value).upper == ('CONTROL 1' or 'CON 1'):
                        #add bits
                        for cell in row[4:]:
                            bits.append(cell.internal_value)    
        #pass over cells that aren't a number, ie values that will never match an address
        except ValueError:
            pass
        except TypeError:
            pass

有没有办法做到这一点?我知道使用row[3]进行的比较将在D列中进行比较,但是如果第一次不正确,我将不知道如何向上移动该列.换句话说,更改row[value]中的值将在行中移动,我需要知道什么值/如何在列中移动.

Is there a way to do this? I know the comparison using row[3] compares in column D, but if it isnt correct the first time, i dont know how to go up the column. Or in other words, changing the value in row[value] moves around the row, and I need to know what value/how to move around the column.

谢谢!

推荐答案

bits = []
min_address = False
for row in ws.iter_rows(row_offset=4,column_offset=3):
    c = row[2]
    d = row[3]
    if not d.internal_value: #d will always have a value if the row isn't blank
        if min_address: 
            break #bits is what you want it to be now
        bits = [] #reset bits every time we hit a new row
        continue #this will just skip to next row

    for bits_cell in row[4:]:
        if bits_cell.internal_value:
            bits.append(bits_cell.internal_value)
    if c.internal_value:
        if c.internal_value == min(address):
            min_address = True #we set it to true, then kept going until blank row

这篇关于使用openpyxl移动到相邻的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆