我正在处理一个生成一些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;
}
发布于 2010-07-22 03:23:46
这里有一个很好的简单的递归函数(基于零索引的数字,意味着0 == A,1 == B,等等)……
function getNameFromNumber($num) {
$numeric = $num % 26;
$letter = chr(65 + $numeric);
$num2 = intval($num / 26);
if ($num2 > 0) {
return getNameFromNumber($num2 - 1) . $letter;
} else {
return $letter;
}
}
如果你想给它加一个索引(1 == A,等等):
function getNameFromNumber($num) {
$numeric = ($num - 1) % 26;
$letter = chr(65 + $numeric);
$num2 = intval(($num - 1) / 26);
if ($num2 > 0) {
return getNameFromNumber($num2) . $letter;
} else {
return $letter;
}
}
测试了从0到10000的数字...
发布于 2010-07-22 05:28:23
为1个-> A、2个-> B等建立索引
function numToExcelAlpha($n) {
$r = 'A';
while ($n-- > 1) {
$r++;
}
return $r;
}
为0 -> A、1 -> B等建立索引
function numToExcelAlpha($n) {
$r = 'A';
while ($n-- >= 1) {
$r++;
}
return $r;
}
在处理字符变量而不是C的算术运算时,PHP遵循Perl的约定。注意,字符变量可以递增,但不能递减。
发布于 2010-07-22 03:17:23
这将用于转换(假设是整数运算),但我同意其他帖子;只需使用base_convert
即可
function numberToColumnName($number)
{
$abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$len = strlen($abc);
$result = "";
while ($number > 0) {
$index = $number % $len;
$result = $abc[$index] . $result;
$number = floor($number / $len);
}
return $result;
}
https://stackoverflow.com/questions/3302857
复制相似问题