在PHP中,如何将Excel样式列名转换为数字?

使用PHP,如何将Excel样式列名称(如“CF”)转换为数字(CF = 84)?这个问题特别适用于PHP . 请不要用另一种语言的答案“欺骗”这个 .

回答(1)

2 years ago

试试这些功能 .

/**
 * 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;
}