本篇提供兩個方法互轉,簡潔又好用,沒有限制數字大小
繼下面這篇文章後,我發現更簡短的方法,提供給大家參考
數字轉換 Excel 欄位英文字母
/**
* Number convert to Excel column letters
*
* 1 = A
* 2 = B
* 3 = C
* 27 = AA
* 1234567789 = CYWOQRM
*
* @link https://vector.cool/php-number-convert-to-excel-column-letters-2
*
* @param int $num 欄數
* @param bool $uppercase 大小寫
* @return void
*/
function num_to_letters($n)
{
$n -= 1;
for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
$r = chr($n % 26 + 0x41) . $r;
return $r;
}
ex:
echo num_to_letters(1); // A
echo num_to_letters(2); // B
echo num_to_letters(3); // C
echo num_to_letters(27); // AA
echo num_to_letters(1234567789); // CYWOQRM
Excel 欄位英文字母轉換回 數字
/**
* Excel column letters convert to Number
*
* A = 1
* B = 2
* C = 3
* AA = 27
* CYWOQRM = 1234567789
*
* @link https://vector.cool/php-number-convert-to-excel-column-letters-2
*
* @param string $letters
* @return mixed
*/
function letters_to_num($a)
{
$l = strlen($a);
$n = 0;
for ($i = 0; $i < $l; $i++)
$n = $n * 26 + ord($a[$i]) - 0x40;
return $n;
}
ex:
echo letters_to_num('A'); // 1
echo letters_to_num('B'); // 2
echo letters_to_num('C'); // 3
echo letters_to_num('AA'); // 27
echo letters_to_num('CYWOQRM'); // 1234567789