Getting cells by coordinate

自古美人都是妖i 提交于 2020-02-21 13:43:46

问题


foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {

    foreach ($worksheet->getRowIterator() as $row) {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(false);
            // I wish
            echo $cellIterator->getCell("A3"); // row: $row, cell: A3
    }
}

I'm looking for a similar method which named getCell above or well-writed PHPExcel documentation.

Thanks.


回答1:


If you have the $row information from RowIterator, you can just easily call:

$rowIndex = $row->getRowIndex ();
$cell = $sheet->getCell('A' . $rowIndex);
echo $cell->getCalculatedValue();

The complete code would be:

foreach($worksheet->getRowIterator() as $row){
    $rowIndex = $row->getRowIndex();

    $cell = $worksheet->getCell('A' . $rowIndex);
    echo $cell->getCalculatedValue();
    $cell = $worksheet->getCell('B' . $rowIndex);
    echo $cell->getCalculatedValue();
}



回答2:


This is what I needed:

function coordinates($x,$y){
 return PHPExcel_Cell::stringFromColumnIndex($x).$y;
}

implementation:

coordinates(5,7); //returns "E7"

Though one could also do this for A-Z columns:

function toNumber($dest)
{
    if ($dest)
        return ord(strtolower($dest)) - 96;
    else
        return 0;
}

function lCoordinates($x,$y){
 $x = $toNumber($x);
 return PHPExcel_Cell::stringFromColumnIndex($x).$y;
}

implementation:

lCoordinates('E',7); //returns "E7"



回答3:


Rather than iterate all the Cells in a row, when not use the rangeToArray() method for the row, and then use array_intersect_key() method to filter only the columns that you want:

$worksheet = $objPHPExcel->getActiveSheet();
$highestColumn = $worksheet->getHighestColumn();

$columns = array_flip(array('A','C','E'));
foreach($worksheet->getRowIterator() as $row)
{
    $range = 'A'.$row->getRowIndex().':'.$highestColumn.$row->getRowIndex();
    $rowData = $worksheet->rangeToArray( $range, 
                                         NULL, 
                                         TRUE,
                                         TRUE,
                                         TRUE);
    $rowData = array_intersect_key($rowData[$row->getRowIndex()],$columns);
    //  do what you want with the row data
}

EDIT

The latest SVN code introduces a number of new methods to th iterators, including the ability to work with ranges, or set the pointer to specific rows and columns



来源:https://stackoverflow.com/questions/9899976/getting-cells-by-coordinate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!