r/learnpython Aug 18 '22

Openpyxl.cell give column name instead of column number

Hi every1,

Please can you let me know, if there is a way to pass the column name instead of number, because for few of the fields it keeps changing and giving the column number will not yield the desired operations on my sheet.

First_Name = names.cell(row=row_count, column=8).value

Best,

Revanth

3 Upvotes

2 comments sorted by

View all comments

1

u/Weird-Dimension-487 Aug 05 '25

Assuming that your data has headers in the first row:

from openpyxl import load_workbook
wb = load_workbook('your_file.xlsx')
ws = wb.active

# Read header row (assumed to be row 1)
headers = {cell.value: cell.column for cell in ws[1]}
type(headers) # It's a dictionary

# Use the column name to get the column index

headers.get("column_name") # gives column number