繁体   English   中英

将数字转换为excel的字符串

[英]Converting a number to a string for excel

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

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

你知道在php中做一个聪明而无痛的方法吗,还是我应该编写自己的自定义函数?

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

$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开始,因此您可能需要稍微调整它以使A从1开始,或者递减您传递的数值

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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