将XY位置表示法转换为电子表格位置表示法

时间:2013-12-19 12:30:30

标签: python

我想知道如何将XY位置表示法(XYPN)转换为电子表格位置表示法(SPN)。例如,我输入(15,3)并输出“P3”。我在python中写了一个SPN-> XYPN函数,虽然我对逆转换感到茫然。这是我到目前为止的代码:

import math

def toCartesian(spreadsheetCoords):
    """Takes spreadsheet coordinates (A1, DI113, etc) and
        and turns them into XY coordinates that start at 0, 0"""
    x, y = 0, 0
    xlist = []
    ychars = ""
    for char in spreadsheetCoords:
        if isChar(char):
            xlist.append(indexInAlphabet(char))
        elif isNumber(char):
            ychars = ychars + char
        else:
            print "Error, invalid value inputted"

    cnt = 0
    for i in range(len(xlist)-1, -1, -1):
        x = x + math.pow(26, cnt)*xlist[i]
        cnt += 1
    y = int(ychars)

    return int(x)-1, y-1

def toSpreadsheetCoords(pos):
    return None


#==========[Util]==========#

def isNumber(char):
    if ord(char) >= 48 and ord(char) <= 57:
        return True
    else:
        return False

def isChar(char):
    if ord(char) >= 65 and ord(char) <= 90:
        return True
    else:
        return False

def indexInAlphabet(char):
    return 26-(90-ord(char))

def charAtIndex(i):
    return chr(65+i)

2 个答案:

答案 0 :(得分:0)

http://python-excel.org可能对您有很大帮助,尤其是def rowcol_to_cell()。他们正在处理excel电子表格。

答案 1 :(得分:0)

以下是基于XlsxWriter模块中的实用程序功能执行此操作的一种方法。

def xl_rowcol_to_cell(row_num, col_num):

    # Removed these 2 lines if your row, col is 1 indexed.
    row_num += 1
    col_num += 1

    col_str = ''

    while col_num:
        remainder = col_num % 26

        if remainder == 0:
            remainder = 26

        # Convert the remainder to a character.
        col_letter = chr(ord('A') + remainder - 1)

        # Accumulate the column letters, right to left.
        col_str = col_letter + col_str

        # Get the next order of magnitude.
        col_num = int((col_num - 1) / 26)

    return col_str + str(row_num)

print xl_rowcol_to_cell(3, 15) # print P4