php換算Excel的Column英文與數字轉換

在匯入Excel的時候,因為讀取到的Col為英文標示,看起來像是26進位,但是是A~Z來表示A=1, B=2,C=3….Z=0…AA=27…

所以匯入的時候,要讀行需透過特殊轉換

底下是我自己想的程式碼,分享給來參考的人

<?php

//Test
for($j=26; $j<=1090; $j=$j+26){
$d = excel_num_to_col($j);
echo “$j”;
print_r($d);
}

//數字轉英文
function excel_num_to_col($num){
for($i=$num; $i>0; $i=($i%26==0)?intval($i/26)-1:intval($i/26)){
$result[] = num_az($i%26);
}
return array_reverse($result);
}

//英文轉數字
function excel_col_to_num($str){
$arr = array_reverse(str_split($str));
foreach((array)$arr as $key => $val){
$result += pow(26, $key)*az_num($val);
}
return $result;
}

//英文轉數字對照
function az_num($str){
if(strtoupper($str)==”A”){return 1;}
if(strtoupper($str)==”B”){return 2;}
if(strtoupper($str)==”C”){return 3;}
if(strtoupper($str)==”D”){return 4;}
if(strtoupper($str)==”E”){return 5;}
if(strtoupper($str)==”F”){return 6;}
if(strtoupper($str)==”G”){return 7;}
if(strtoupper($str)==”H”){return 8;}
if(strtoupper($str)==”I”){return 9;}
if(strtoupper($str)==”J”){return 10;}
if(strtoupper($str)==”K”){return 11;}
if(strtoupper($str)==”L”){return 12;}
if(strtoupper($str)==”M”){return 13;}
if(strtoupper($str)==”N”){return 14;}
if(strtoupper($str)==”O”){return 15;}
if(strtoupper($str)==”P”){return 16;}
if(strtoupper($str)==”Q”){return 17;}
if(strtoupper($str)==”R”){return 18;}
if(strtoupper($str)==”S”){return 19;}
if(strtoupper($str)==”T”){return 20;}
if(strtoupper($str)==”U”){return 21;}
if(strtoupper($str)==”V”){return 22;}
if(strtoupper($str)==”W”){return 23;}
if(strtoupper($str)==”X”){return 24;}
if(strtoupper($str)==”Y”){return 25;}
if(strtoupper($str)==”Z”){return 26;}
}

//數字轉英文對照
function num_az($num){
if($num==1){return “A”;}
if($num==2){return “B”;}
if($num==3){return “C”;}
if($num==4){return “D”;}
if($num==5){return “E”;}
if($num==6){return “F”;}
if($num==7){return “G”;}
if($num==8){return “H”;}
if($num==9){return “I”;}
if($num==10){return “J”;}
if($num==11){return “K”;}
if($num==12){return “L”;}
if($num==13){return “M”;}
if($num==14){return “N”;}
if($num==15){return “O”;}
if($num==16){return “P”;}
if($num==17){return “Q”;}
if($num==18){return “R”;}
if($num==19){return “S”;}
if($num==20){return “T”;}
if($num==21){return “U”;}
if($num==22){return “V”;}
if($num==23){return “W”;}
if($num==24){return “X”;}
if($num==25){return “Y”;}
if($num==0){return “Z”;}
}
?>

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *