Home » excel » python – converting excel positioning to numbers

python – converting excel positioning to numbers

Posted by: admin May 14, 2020 Leave a comment


I’m a new bee in python and am trying to convert some excel coordinates say A12 to a number how can I separate the A from 12 to do that? or is there any other way?


How to&Answers:

If you’re dealing with Excel files, then it’s worth having the xlrd (reading), xlwt (writing) and xlutils (utilities for copying/filtering sheets etc…) libraries. The easiest way to install those is to pip install xlutils and you’ll get the others as dependencies.

Then you can use:

>>> import xlwt
>>> xlwt.Utils.cell_to_rowcol2('A12') # Your original coords
(11, 0)
>>> xlwt.Utils.cell_to_rowcol2('AB31') # ex by @nooodl
(30, 27)

Note these are zero-based 2-tuple’s of (row number, column number)

You also get the inverse for free:

>>> xlwt.Utils.rowcol_to_cell(30, 27)

As well as other goodies including absolute, relative ranges etc… etc…


Try something like this:

import re

def column_index(column_name):
    acc = 0
    for c in column_name:
        assert 'A' <= c <= 'Z'
        acc = acc * 26 + (ord(c) - ord('A') + 1)
    return acc

def cell_coords(cell):
    match = re.match(r'([A-Z]+)(\d+)', cell)
    if not match:
        raise ValueError('Invalid cell format: ' + cell)
    x = column_index(match.group(1))
    y = int(match.group(2))
    return (x, y)

assert cell_coords('AB31') == (28, 31)