Get Excel-Style Column Names from Column Number

前端 未结 8 1593
慢半拍i
慢半拍i 2020-12-01 12:38

This is the code for providing the COLUMN name when the row and col ID is provided but when I give values like row = 1 and col = 104, it should return CZ<

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 13:01

    Here's another way to get excel column names without a loop, using a pandas multiindex dataframe. This is a modification of a generalized base-to-base converter, so the code is a little lengthier than some of the other options, but I think it's effective:

    def xlcolumn(num):
        base = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        baseln = len(base)
        idx = [""]+base
        num = num-1
    
        # create pandas multiindex using idx, base
        # current excel version has 16384 columns (A --> XFD), so multiindex needs to have a minimum of 3 levels:
        #   (26x26x26 = 17576 > 16384 columns) 
    
        index = pd.MultiIndex.from_product([idx, idx, idx],names=['level 1', 'level 2', 'level 3'])
        df = pd.DataFrame(index = index)
        df = df.drop("",level = 'level 3')
        df = df.iloc[:baseln].append(df.drop("",level = 'level 2'))
        df['val']=1
    
        if num < baseln:
            xlcol = str(df.iloc[num].name[2])
        elif num >= baseln and num < baseln**2:
            xlcol = str(df.iloc[num].name[1])+str(df.iloc[num].name[2])
        else:
            xlcol = str(df.iloc[num].name[0])+str(df.iloc[num].name[1])+str(df.iloc[num].name[2])
    
        return xlcol
    
    

提交回复
热议问题