Ad Code

PHP code to convert a number to an Excel column letter

I was looking for a good way to convert a number to the Excel column letter, for example:

1 -> A
26 -> Z
27 -> AA
28 -> AB
800 -> ADT

etc.

After searching on Google, I could not find any algorithm I want. (The closest one can handle up to two letters, i.e., ZZ. It will crash if the number is too large.). So I ended up creating my own.

Basically, you can think of this problem as a 26 based number conversion. Here is the php version. It should be pretty simple to convert it to a different language. Let me know if you have any problem.

function columnLetter($c){
    $c = intval($c);
    if($c <= 0) return '';
    $letter = '';
    while($c != 0){
        $p = ($c - 1) % 26;
        $c = intval(($c - $p) / 26);
        $letter = chr(65 + $p) . $letter;
    }
    return $letter;
}

function num2alpha($n){
    for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
    $r = chr($n%26 + 0x41) . $r;
    return $r;
}

Post a Comment

0 Comments