php 类似excel,php – 获取数字的类似excel的列名的算法

我正在一个脚本生成一些Excel文档,我需要转换一个数字到它的列名称等价。例如:

1 => A

2 => B

27 => AA

28 => AB

14558 => UMX

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

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的实现工作相当精细。但是,我要添加这个很好的短:

function num2alpha($n)

{

for($r = ""; $n >= 0; $n = intval($n / 26) - 1)

$r = chr($n%26 + 0x41) . $r;

return $r;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值