How to use field name or column header in openpyxl?

北城以北 提交于 2019-12-03 13:47:11

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

You can access cells from the first row and and column using the sheet.cell(row=#, column = #) syntax. For example:

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)

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]] 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!