Mapping Excel column name to numeric order is kind of a crappy thing, because there's no 0
in A-Z...
Anyway, I did come up with two functions to convert them back and forth:
function calcCol($col) //character to number
{
if(is_numeric($col)) return intval($col);
$col=array_reverse(str_split(strtoupper(preg_replace("/[^a-z]/i","",$col))));
$num=0;
foreach($col as $i=>$ch)
{
$num+=(ord($ch)-ord('A')+1)*pow(27,$i);
}
$num-=ceil($num/27)-1;
return $num;
}
function getCol($col) //number to character
{
if(preg_match("/^[a-z]+$/i",$col)) return strtoupper($col);
$col=abs(intval($col));
$col+=ceil($col/26)-1;
$str="";
while($col>0)
{
$tmp=$col%27;
$str=chr($tmp-1+ord('A')).$str;
$col=floor($col/27);
}
return $str;
}
Explanation:
Consider A-Z as a 27-based numeric system with a missing/hidden 0
;
And after converting from character to number, removes those hidden 0
s by counting how many 27 is "counted" (ceil($num/27)
);
And before converting from number to character, add those hidden 0
s back by counting how many 26 is "counted" (ceil($col/26)
).