使用PHP,如何将Excel样式列名称(如“CF”)转换为数字(CF = 84)? 这个问题特别适用于PHP。请不要用不同的语言来回答这个问题。在PHP中,如何将Excel样式列名转换为数字?
回答
试试这些功能。
/**
* Convert Excel style column names into numbers.
* @param string $column Excel style column name like AA or CF
* @return integer Number with A being 1 and AA being 27
*/
function alpha2num($column) {
$number = 0;
foreach(str_split($column) as $letter){
$number = ($number * 26) + (ord(strtolower($letter)) - 96);
}
return $number;
}
/**
* Access array value with Excel style column name.
* @param array $array The array to access
* @param string $column Excel style column name like AA or CF
* @return mixed Value found at the column
*/
function alpha_col($array, $column){
$i = alpha2num($column) - 1;
return isset($array[$i]) ? $array[$i] : false;
}
[PHPExcel有点不同,如果你有兴趣。](https://github.com/PHPOffice/PHPExcel/blob/1c8c2379ccf5ab9dd7cb46be965821d22173bcf4/Classes/PHPExcel/Cell.php#L790) –
我看到了,但对我来说它看起来像一个肮脏的方法,虽然强大。 – azBrian
我只是觉得你可能对他们对'ord'和'strtolower'性能影响的一些观察感兴趣。我同意你的方式看起来更整洁。 –
欺骗:http://stackoverflow.com/questions/5554369/php-how-to-output-list-like-this-aa-ab-ac-all-the-way-to-zzzy- zzzz-zzzza – nogad
可能的重复[Excel专栏名称列名](http://stackoverflow.com/questions/10106465/excel-column-number-from-column-name) – MarianD
@nogad,可能但是当我在搜索对于解决方案,我没有发现这个问题,因为它是针对不同的实用程序。 – azBrian