编辑
假设这些是您要查找的标题名称:
colnames = ['Header1', 'Header2', 'Header3']
找到这些列的索引:
col_indices = {n for n, cell in enumerate(sheet.rows[0]) if cell.value in colnames}
现在迭代剩余的行:
for row in sheet.rows[1:]: for index, cell in enumerate(row): if index in col_indices: if cell.value.upper() == 'OldValue1': cell.value = 1 print(cell.value) elif cell.value.upper() == 'OldValue2': cell.value = 2 print(cell.value)
使用字典而不是集合来保持列名称:
col_indices = {n: cell.value for n, cell in enumerate(sheet.rows[0]) if cell.value in colnames} for row in sheet.rows[1:]: for index, cell in enumerate(row): if index in col_indices: print('col: {}, row: {}, content: {}'.format( col_indices[index], index, cell.value)) if cell.value.upper() == 'OldValue1': cell.value = 1 elif cell.value.upper() == 'OldValue2': cell.value = 2
老答案
这使您的if
陈述更短:
if cellObj.column in 'HILM': print(cellObj.value),
对于多字母列坐标,您需要使用列表:
if cellObj.column in ['H', 'AA', 'AB', 'AD']: print(cellObj.value),