Home > Mobile >  Get Excel column letter based on column header - Python
Get Excel column letter based on column header - Python

Time:09-30

This seems relatively straight forward, but I have yet to find a duplicate that answers my question, or a method with the needed functionality.

I have an Excel spreadsheet where each column that contains data has a unique header. I would like to use pandas to get the letter key of the column by passing this header string into a function.

For example, if I pass "Output Parameters" to the function, I would like to return "M":

enter image description here

The closest thing that I have found is the xlsxwriter.utility.xl_col_to_name(index) method outlined in the second answer in Convert spreadsheet number to column letter

This is very similar to what I am trying to do, however the column numbers within my sheets will not remain constant (unlike the headers, which will). This being said, a method that can return the column number based on the header would also work, as I would then be able to apply the above.

Does pandas or xlsxwriter have a method that can handle the above case?

CodePudding user response:

You can try:

import xlsxwriter
col_no = df.columns.get_loc("col_name")
print(xlsxwriter.utility.xl_col_to_name(col_no))
  • Related