1

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?

Pang
  • 9,564
  • 146
  • 81
  • 122
rythm
  • 13
  • 1
  • 5
  • Follow the loops. Also, you formatted the loops differntly. Usually you see `for(int i = 0; i < highest; i++)` for a rough version (start at 0 and use < instead of <=, – Evan Carslake Oct 01 '15 at 04:56

1 Answers1

3
$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 <=

Mark Baker
  • 209,507
  • 32
  • 346
  • 385