數字轉換 Excel 欄位英文字母,例如 1 = A , 2 = B , 27 = AA
Excel 欄位英文字母轉換回 數字 , 例如 A = 1 , B = 2 , AA = 27
本篇提供兩個方法互轉,簡潔又好用,沒有限制數字大小
數字轉換 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/
*
* @param int $num 欄數
* @param bool $uppercase 大小寫
* @return void
*/
function num_to_letters( $num , $uppercase = true):string {
$letters = '';
while ($num > 0) {
$code = ($num % 26 == 0) ? 26 : $num % 26;
$letters .= chr($code + 64);
$num = ($num - $code) / 26;
}
return ($uppercase) ? strtoupper(strrev($letters)) : strrev($letters);
}
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/
*
* @param string $letters
* @return mixed
*/
function letters_to_num( string $letters ) {
$num = 0;
$arr = array_reverse(str_split($letters));
for ($i = 0; $i < count($arr); $i++) {
$num += (ord(strtolower($arr[$i])) - 96) * (pow(26,$i));
}
return $num;
}
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
https://stackoverflow.com/a/25214690/6784662