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

sta*_*hna 7 python excel openpyxl

请参阅下面的代码.这段代码效果很好,但我想做两件事.有一点是我做了if语句或比实际更短的例如.我有很多像这样的列,而不是彼此相邻.我希望它更短.此外,有时我可能不知道确切的专栏信.

所以我想知道是否有办法知道列名或标题.就像最顶行的值一样.因此,如果它位于指定的列中,我可以测试以查看它是否始终在该单元格上执行函数.我找不到openpyxl函数来做列名.不确定它是否理解第一行与休息不同.我想也许如果不是我可以尝试在第一行做测试,但不明白如何做到这一点.

那么有没有办法调用列名?或者如果没有办法调用列名来测试,有人可以帮我做第一行检查,看看它是否有价值?然后改变正确的行我在?这有意义吗?

所以而不是代码说:

if cellObj.column == 'H' or ...
Run Code Online (Sandbox Code Playgroud)

它会说:

if cellObj.column_header == 'NameOfField or ...
Run Code Online (Sandbox Code Playgroud)

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

if this cell has column where first row value is 'NameOfField' ...
Run Code Online (Sandbox Code Playgroud)

请帮助我们做到这一点的最好方法.我查看了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)
Run Code Online (Sandbox Code Playgroud)

Mik*_*ler 5

编辑

假设这些是您要查找的标题名称:

colnames = ['Header1', 'Header2', 'Header3']
Run Code Online (Sandbox Code Playgroud)

找到这些列的索引:

col_indices = {n for n, cell in enumerate(sheet.rows[0]) if cell.value in colnames}
Run Code Online (Sandbox Code Playgroud)

现在迭代剩余的行:

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)
Run Code Online (Sandbox Code Playgroud)

使用字典而不是集合来保持列名称:

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
Run Code Online (Sandbox Code Playgroud)

老答案

这使您的if陈述更短:

if cellObj.column in 'HILM':
    print(cellObj.value),
Run Code Online (Sandbox Code Playgroud)

对于多字母列坐标,您需要使用列表:

if cellObj.column in ['H', 'AA', 'AB', 'AD']:
    print(cellObj.value),
Run Code Online (Sandbox Code Playgroud)