如何使用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();

返回一个字符串,其中包含最高列的地址(例如:"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,然后使用!=而不是<=进行比较