我想在已经找到的单元格旁边的单元格中找到excel单元格的值。
我的代码:
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)然后输出为:
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。
感谢大家的帮助!
发布于 2020-06-26 03:58:30
访问相邻小区
如果使用.cell() method,则可以避免使用字母,只需在列号上加一,您可以从for循环访问该列号:
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编辑成这样会行得通:
if re.search("^(BMS_RACK14.74)$", currentSheet[cell_name].value):
[...]https://stackoverflow.com/questions/62582822
复制相似问题