How to use field name or column header in openpyxl?

后端 未结 4 1076
情深已故
情深已故 2021-02-15 14:42

See my code below. This code works very well, but I would like to do two things. One thing is I made if statement with or much shorter than actual for example. I have many colum

4条回答
  •  悲&欢浪女
    2021-02-15 15:35

    EDIT

    Assuming these are the header names you are looking for:

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

    Find the indices for these columns:

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

    Now iterate over the remain rows:

    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)
    

    Use a dictionary instead of a set to keep the column names around:

    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
    

    Old answer

    This makes your if statement shorter:

    if cellObj.column in 'HILM':
        print(cellObj.value),
    

    For multi letter column coordinates you need to use a list:

    if cellObj.column in ['H', 'AA', 'AB', 'AD']:
        print(cellObj.value),
    

提交回复
热议问题