rythm
rythm

Reputation: 13

How to get column index of current cell of an excel using PHPExcel?

I am trying to get the index of the current active cell using PHPExcel. What I've tried so far is:

// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();
    for ($row = 1; $row <= $highestRow; $row++){ 
        for($col = 1; $col <= $highestColumn; $col++){
           $cell = $sheet->getCellByColumnAndRow($col, $row);
           $colIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn());
            echo $colIndex;
      }
}

It doesn't display anything on the browser. Can anyone help me with this?

Upvotes: 1

Views: 5230

Answers (1)

Mark Baker
Mark Baker

Reputation: 212402

$highestColumn = $sheet->getHighestColumn();

Returns a string containing the address of the highest column (e.g. "IV", but you're counting $col as a numeric, and comparing it against that string, so the loop isn't doing much of anything. (PHP loose comparison rules)


Iterate using $col as a character-based column address starting with "A"

// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); 
$highestColumn = $sheet->getHighestColumn();
$highestColumn++;
    for ($row = 1; $row <= $highestRow; $row++){ 
        for($col = 'A'; $col != $highestColumn; $col++){
           $cell = $sheet->getCellByColumnAndRow($col, $row);
           $colIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn());
            echo $colIndex;
      }
}

And note that you will need to increment $highestColumn and then do the comparison using != rather than <=

Upvotes: 3

Related Questions