PHPExcel how to get column index from cell

2020-05-30 05:37发布

问题:

PHPExcel $cell->getColumn() returns 'A', 'B', 'C', ...

which is the best way to get the integer (0, 1, 2, ...) from the cell.

This function doesn't exist.

$colIndex = $cell->getColumnIndex();

So what is the alternative withoput converting chr to ascii ?

回答1:

$colIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn());


回答2:

You can get column index while iterate.

$xls = PHPExcel_IOFactory::load($fn);
$xls->setActiveSheetIndex(0);
$sheet = $xls->getActiveSheet();

foreach($sheet->getRowIterator() as $row)
{
    foreach($row->getCellIterator() as $key => $cell)
    {
        echo $key; // 0, 1, 2...
        echo $cell->getCalculatedValue(); // Value here
    }
}


回答3:

If you want to get decrement cell address using this function, you have to use another function with this function as follows.

<?php
echo columnLetter("AB");

function columnLetter($c){


$letter="";
    $c = intval(columnNumber($c));
    if ($c<=0) return '';

    while($c != 0){
       $p = ($c - 1) % 26;
       $c = intval(($c - $p) / 26);
       $letter = chr(65 + $p) . $letter;
    }

    return $letter;

}

function columnNumber($col){

    $col = str_pad($col,2,'0',STR_PAD_LEFT);
    $i = ($col{0} == '0') ? 0 : (ord($col{0}) - 64) * 26;
    $i += ord($col{1}) - 64;

    return $i-1;

}
?>


标签: php phpexcel