簡體   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