bpeterso2000
4/9/2014 - 2:47 PM

Convert between column numbers & spreadsheet column names (alpha ID's)

Convert between column numbers & spreadsheet column names (alpha ID's)

""" 
SPREADSHEET-STYLE COLUMN HEADERS
"""
from collections import OrderedDict

def id2num(s):
    """ spreadsheet column name to number
    ref: http://stackoverflow.com/questions/7261936

   :param s: str -- spreadsheet column alpha ID (i.e. A, B, ... AA, AB,...)
   :returns: int -- spreadsheet column number (zero-based index)

    >>> id2num('A')
    0
    >>> id2num('B')
    1
    >>> id2num('XFD')
    16383
    >>>

    """
    n = 0
    for ch in s.upper():
        n = n * 26 + (ord(ch) - 65) + 1
    return n - 1


def num2id(n):
    """
    ref: http://stackoverflow.com/questions/181596

   :param n: int -- spreadsheet column number (zero-based index)
   :returns: int -- spreadsheet column alpha ID (i.e. A, B, ... AA, AB,...)

    >>> num2id(0)
    'A'
    >>> num2id(1)
    'B'
    >>> num2id(16383)
    'XFD'

    """
    s = ''
    d = n + 1
    while d:
        m = (d - 1) % 26
        s = chr(65 + m) + s
        d = int((d - m) / 26)
    return s


class AlphaID:

    def __init__(self, num=99):
        self.num = num
        self.create(num)

    def create(self, stop=None, start=0):
        if stop is None:
            stop = self.num
        self.ids = tuple(map(num2id, range(start, stop)))

    def get_(self, n=None):
        if not n or n == len(self.ids):
            return self.ids
        if n < len(self.ids):
            return self.ids[:n]
        return self.ids + self.create(n - len(self.ids), start=n)

    def as_dict(self, origin=0):
        return OrderedDict((i, n) for n, i in enumerate(self.ids, origin))


def get_alphaids(num=99):
    return AlphaID(num).get_(num)