Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a number to a string for excel

I need to convert an integer (number of columns) into a string according to excel column naming scheme, like so:

1 => A
2 => B
25 => Z
26 => AA
28 => AC
51 => BA

Do you know of a smart and painless way to do this within php, or should I go about writing my own custom function?

like image 595
Skarlinski Avatar asked Mar 24 '26 05:03

Skarlinski


1 Answers

You can do it with a simple loop:

$number = 51;
$letter = 'A';
for ($i = 1; $i <= $number; ++$i) {
    ++$letter;
}
echo $letter;

though if you're doing this frequently with higher values, it'll be a bit slow

or look at the stringFromColumnIndex() method in PHPExcel's Cell object that is used for exactly this purpose

public static function stringFromColumnIndex($pColumnIndex = 0) {
    //  Using a lookup cache adds a slight memory overhead, but boosts speed
    //    caching using a static within the method is faster than a class static,
    //    though it's additional memory overhead
    static $_indexCache = array();

    if (!isset($_indexCache[$pColumnIndex])) {
        // Determine column string
        if ($pColumnIndex < 26) {
            $_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex);
        } elseif ($pColumnIndex < 702) {
            $_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) .
                chr(65 + $pColumnIndex % 26);
        } else {
            $_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) .
                chr(65 + ((($pColumnIndex - 26) % 676) / 26)) .
                chr(65 + $pColumnIndex % 26);
        }
    }
    return $_indexCache[$pColumnIndex];
}

Note that the PHPExcel method indexes from 0, so you might need to adjust it slightly to give A from 1, or decrement the numeric value that you pass

There is also a corresponding columnIndexFromString() method in the cell object that returns a numeric from a column address

like image 90
Mark Baker Avatar answered Mar 26 '26 17:03

Mark Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!