3

我需要根据excel列命名方案将整数(列数)转换为字符串,如下所示:

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

您是否知道在 php 中执行此操作的一种智能且轻松的方法,还是我应该编写自己的自定义函数?

4

2 回答 2

3

你可以用一个简单的循环来做到这一点:

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

但是,如果您经常使用较高的值执行此操作,则会有点慢

或查看用于此目的的 PHPExcel 的 Cell 对象中的 stringFromColumnIndex() 方法

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];
}

请注意,PHPExcel 方法从 0 开始索引,因此您可能需要稍微调整它以从 1 中给出 A,或者减少您传递的数值

在单元格对象中还有一个对应的 columnIndexFromString() 方法,它从列地址返回一个数字

于 2013-09-01T14:23:35.860 回答
1

使用纯 PHP 也可以很容易地完成:

function getCellFromColnum($colNum) {
    return ($colNum < 26 ? chr(65+$colNum) : chr(65+floor($colNum/26)-1) . chr(65+ ($colNum % 26)));
}
于 2016-03-11T16:57:15.673 回答