如何使用 PHPExcel 获取 excel 当前单元格的列索引?

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

我正在尝试使用 PHPExcel 获取当前活动单元格的索引。到目前为止我尝试过的是:

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

在浏览器上不显示任何内容。谁能帮我解决这个问题?

$highestColumn = $sheet->getHighestColumn();

Returns 一个 string 包含最高列的地址(例如 "IV",但您将 $col 算作数字, 并将其与该字符串进行比较,因此循环没有做任何事情。(PHP 宽松的比较规则)


使用 $col 作为以 "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;
      }
}

请注意,您需要递增 $highestColumn,然后使用 != 而不是 <=

进行比较