Translate a column index into an Excel Column Name

前端 未结 15 2228
花落未央
花落未央 2020-11-27 20:41

Given a columns\' index, how can you get an Excel column name?

The problem is trickier than it sounds because it\'s not just base-26. The columns

相关标签:
15条回答
  • 2020-11-27 21:10

    The php version, thank's to this post to help me figure it out ! ^^

    /**
     * Get excel column name
     * @param index : a column index we want to get the value in excel column format
     * @return (string) : excel column format
     */
    function getexcelcolumnname($index) {
        //Get the quotient : if the index superior to base 26 max ?
        $quotient = $index / 26;
        if ($quotient >= 1) {
            //If yes, get top level column + the current column code
            return getexcelcolumnname($quotient-1). chr(($index % 26)+65);
        } else {
            //If no just return the current column code
            return chr(65 + $index);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 21:10

    This JavaScript version shows that at its core it's a conversion to base 26:

    function colName(x)
    {
        x = (parseInt("ooooooop0", 26) + x).toString(26);
        return x.slice(x.indexOf('p') + 1).replace(/./g, function(c)
        {
            c = c.charCodeAt(0);
            return String.fromCharCode(c < 64 ? c + 17 : c - 22);
        });
    }
    

    The .toString(26) bit shows that Joel Coehoorn is wrong: it is a simple base conversion.

    (Note: I have a more straight-forward implementation based on Dana's answer in production. It's less heavy, works for larger numbers although that won't affect me, but also doesn't show the mathematical principle as clearly.)

    P.S. Here's the function evaluated at important points:

    0 A
    1 B
    9 J
    10 K
    24 Y
    25 Z
    26 AA
    27 AB
    700 ZY
    701 ZZ
    702 AAA
    703 AAB
    18276 ZZY
    18277 ZZZ
    18278 AAAA
    18279 AAAB
    475252 ZZZY
    475253 ZZZZ
    475254 AAAAA
    475255 AAAAB
    12356628 ZZZZY
    12356629 ZZZZZ
    12356630 AAAAAA
    12356631 AAAAAB
    321272404 ZZZZZY
    321272405 ZZZZZZ
    321272406 AAAAAAA
    321272407 AAAAAAB
    8353082580 ZZZZZZY
    8353082581 ZZZZZZZ
    8353082582 AAAAAAAA
    8353082583 AAAAAAAB
    
    0 讨论(0)
  • 2020-11-27 21:12

    in python, with recursion. translated from Joey's answer. so far, it's tested to work up to GetExcelByColumn(35) = 'AI'

    def GetExcelColumn(index):
    
        quotient = int(index / 26)
    
        if quotient > 0:
            return GetExcelColumn(quotient) + str(chr((index % 26) + 64))
    
        else:
            return str(chr(index + 64))
    
    0 讨论(0)
提交回复
热议问题