首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用python在excel单元格中查找已找到的另一个单元格中的值?

如何使用python在excel单元格中查找已找到的另一个单元格中的值?
EN

Stack Overflow用户
提问于 2020-06-26 03:20:44
回答 1查看 245关注 0票数 0

我想在已经找到的单元格旁边的单元格中找到excel单元格的值。

我的代码:

代码语言:javascript
复制
file = openpyxl.load_workbook('test1.xlsx', read_only = True)
allSheetNames = file.sheetnames

print("All sheet names {}" .format(file.sheetnames))

for sheet in allSheetNames:
    print('Current sheet name is {}'.format(sheet))
    currentSheet = file[sheet]

    for row in range(1, currentSheet.max_row + 1):
        #print row
        for column in 'CDEF':  #Add or remove if needed
            cell_name = '{}{}'.format(column,row)
        
            if currentSheet[cell_name].value == 'BMS_RACK14.74': #<- working
                 print 'Cell position {} has value {}'.format(cell_name, currentSheet[cell_name].value)

然后输出为:

代码语言:javascript
复制
All sheet names ['Sheet1', 'Sheet2']
Current sheet name is Sheet1
Current sheet name is Sheet2
Cell position E5 has value BMS_RACK14.74
Cell position D7 has value BMS_RACK14.74
Cell position E7 has value BMS_RACK14.74

我希望获得E5、D7和E7 (因此在本例中为F5、E7和F7)旁边的单元格中的值。要在我的代码中添加什么才能获得此值?我找不到解决办法。或者有没有更好的整体解决方案?

另外,我想知道我在搜索“BMS_RACK14.74”时是如何包含通配符的,比如BMS_RACK14?74或BMS_RACK14*74。

感谢大家的帮助!

EN

回答 1

Stack Overflow用户

发布于 2020-06-26 03:58:30

访问相邻小区

如果使用.cell() method,则可以避免使用字母,只需在列号上加一,您可以从for循环访问该列号:

代码语言:javascript
复制
for row in range(1, currentSheet.max_row + 1):
        #print row
        for column in 'CDEF':  #Add or remove if needed
            cell_name = '{}{}'.format(column,row)
        
            if currentSheet[cell_name].value == 'BMS_RACK14.74': #<- working
                 print('Cell position {} has value {}'.format(cell_name, currentSheet[cell_name].value))
                 print("Neighbouring cell's value: {}".format(currentSheet.cell(row=row, column=column+1))

通配符提示

这里的提示是Regex。W3Schools有a great tutorial

我想把你的if编辑成这样会行得通:

代码语言:javascript
复制
if re.search("^(BMS_RACK14.74)$", currentSheet[cell_name].value):
[...]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62582822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档