如何在openpyxl中使用字段名称或列标题?

看到我的代码如下。 这个代码工作得很好,但我想做两件事情。 有一件事是我做了,如果声明比实际或短得多比如。 我有很多这样的列,并不是所有的彼此相邻。 我希望它更短。 此外,有时我可能不知道确切的列字母。

所以我想知道是否有办法知道列名或标题。 就像在最顶端的价值观一样。 所以我可以testing,看看它是否是这些值之一,如果它在指定的列中,总是对该单元格执行函数。 我无法findopenpyxl函数来做列名。 不知道是否理解第一行与rest不同。 我想也许如果不是,我可以尝试做第一排testing,但不明白如何做到这一点。

那么有没有办法调用列名? 或者如果没有办法调用列名testing,有人可以帮我做第一行检查,看看它是否有价值? 那么改变正确的行我在? 这是否有道理?

所以,而不是代码说:

if cellObj.column == 'H' or ... 

它会说:

 if cellObj.column_header == 'NameOfField or ... 

或者如果不能这样做,那么:

 if this cell has column where first row value is 'NameOfField' ... 

请帮助最好的方式来做到这一点。 我已经看到了stackoverflow和书籍和博客网站,但似乎并没有调用列名(不是列的字母)的方式。

 for row in sheet.iter_rows(): for cellObj in row: if cellObj.column == 'H' or cellObj.column == 'I' or cellObj.column == 'L' or cellObj.column == 'M': print(cellObj.value), if cellObj.value.upper() == 'OldValue1': cellObj.value = 1 print(cellObj.value) elif cellObj.value.upper() == 'OldValue2': cellObj.value = 2 print(cellObj.value) 

编辑

假设这些是您正在寻找的标题名称:

 colnames = ['Header1', 'Header2', 'Header3'] 

find这些列的索引:

 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), 

您可以使用sheet.cell(row =#,column =#)语法访问第一行和第一列的单元格。 例如:

 for row in enumerate(sheet.iter_rows()): for j, cellObj in enumerate(row): header_cell = sheet.cell(row=1, column=j) if cellObj.column in ['H', 'I', 'L', 'M', 'AA', 'AB']: print(cellObj.value), if cellObj.value.upper() == 'OldValue1': cellObj.value = 1 print(cellObj.value) elif cellObj.value.upper() == 'OldValue2': cellObj.value = 2 print(cellObj.value)