PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 5, 2022

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

 October 05, 2022     php, phpexcel     No comments   

Issue

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?


Solution

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



Answered By - Mark Baker
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing