How to use field name or column header in openpyxl?

后端 未结 4 1075
情深已故
情深已故 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:11

    Since row returns a generator, you can easily extract headers in the first iteration, treat them as you need, and then continue to consume it. For instance:

    headers = [cell.value for cell in next(sheet.rows)]
    # find indexes of targeted columns
    cols = [headers.index(header) for header in 'HILM']
    
    conv = {'OldValue1': 1, 'OldValue2': 2}
    
    for row in sheet.rows:
        values = [cell.value for cell in row]
        for col in cols:
            values[col] = conv[values[col]] 
    

提交回复
热议问题