简体   繁体   中英

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?

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

It can also be done quite easily with pure PHP:

function getCellFromColnum($colNum) {
    return ($colNum < 26 ? chr(65+$colNum) : chr(65+floor($colNum/26)-1) . chr(65+ ($colNum % 26)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM