首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取数字的类excel列名的算法

获取数字的类excel列名的算法
EN

Stack Overflow用户
提问于 2010-07-22 03:09:10
回答 7查看 57.9K关注 0票数 107

我正在处理一个生成一些Excel文档的脚本,我需要将一个数字转换为与其等效的列名。例如:

代码语言:javascript
复制
1 => A
2 => B
27 => AA
28 => AB
14558 => UMX

我已经写了一个这样做的算法,但我想知道是否有更简单或更快的方法来做到这一点:

代码语言:javascript
复制
function numberToColumnName($number){
    $abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $abc_len = strlen($abc);

    $result_len = 1; // how much characters the column's name will have
    $pow = 0;
    while( ( $pow += pow($abc_len, $result_len) ) < $number ){
        $result_len++;
    }

    $result = "";
    $next = false;
    // add each character to the result...
    for($i = 1; $i<=$result_len; $i++){
        $index = ($number % $abc_len) - 1; // calculate the module

        // sometimes the index should be decreased by 1
        if( $next || $next = false ){
            $index--;
        }

        // this is the point that will be calculated in the next iteration
        $number = floor($number / strlen($abc));

        // if the index is negative, convert it to positive
        if( $next = ($index < 0) ) {
            $index = $abc_len + $index;
        }

        $result = $abc[$index].$result; // concatenate the letter
    }
    return $result;
}

你知道更好的方法吗?也许有什么能让它变得更简单?或者是性能的提升?

编辑

ircmaxell的实现工作得很好。但是,我将添加这个很好的简短的:

代码语言:javascript
复制
function num2alpha($n)
{
    for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
        $r = chr($n%26 + 0x41) . $r;
    return $r;
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3302857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档