I'm trying to covert a coordinate value in excel to a row number and column number in openpyxl.
For example if my cell coordinate is D4 I want to find the corresponding row and column numbers to use for future operations, in the case row = 3, column = 3. I can get the row number easily using ws.cell('D4').row
which returns 4
then it's just a matter of subtracting 1. But a similar argument ws.cell('D4').column
returns D
and I don't know how to easily get this into int form for subsequent operations. So I turn to you wise folks of stackoverflow. Can you help me?
Old topic, but the answer is not correct!
dylnmc method was a good one, but has some errors. The calculated row for cell coords like "AA1" or "AAB1" is not correct.
Below is the corrected version as a function.
NOTE: This function returns the real coordinated. If you want to use it for example in ExcelWriter, both ROW and COL should be deducted by one. So replace the last line with return(row-1,col-1)
For example 'AA1' is [1,27] and 'AAA1' is [1,703]; but the python must have them as [0,26] and [0,702].
What you want is
openpyxl.utils.coordinate_from_string()
andopenpyxl.utils.column_index_from_string()
This is building off of Nathan's answer. Basically, his answer does not work properly when the row and/or column is more than one character wide. Sorry - I went a little over board. Here is the full script:
Tl;dr with a bunch of comments...
openpyxl has a function called get_column_letter that converts a number to a column letter.
1 --> A
50 --> AX
1234-- AUL
I have been using it like:
You could just use pure Python:
This uses the
ord
function which takes a character and returns its ASCII code. In ASCII the letterA
is 65,B
is 66 and so on.