0

I have to iterate through all rows of first two columns of a xls document. The problem is that first column of this specific document is "G" with and index of 7.

Is there any way of getting the first column index because I don't want to hard-code it.

My loop:

$spreadsheet =\PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$worksheet = $spreadsheet->getActiveSheet();

$highestRow = $worksheet->getHighestRow();

$rows = [];
for ($row = 1; $row <= $highestRow; ++$row) {
    // I WANT TO REPLACE HARD-CODED VALUES OF 7 AND 8
    // WITH $firstCol and $firstCol+1
    for ($col = 7; $col <= 8; ++$col) { 
        $value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
        $rows[$row][$col] = $value;
    }
}
stollr
  • 6,534
  • 4
  • 43
  • 59
failedCoder
  • 1,346
  • 1
  • 14
  • 38
  • 2
    Column `G` is not the "first column". It may be the first column with data that you are interested in but `A` is the first column. If the first 6 columns are empty you could go through the columns until you reach the first non-empty column and assume that that is your first column. I think using hard coded columns is probably safer based on your description of the situation. – Dave May 14 '19 at 14:47
  • Possible duplicate of [Ignore empty cells PHPExcel](https://stackoverflow.com/questions/12285511/ignore-empty-cells-phpexcel) – miken32 May 14 '19 at 21:24

1 Answers1

2

You can add a while loop to skip empty cells. Try this:

$rows = [];
for ($row = 1; $row <= $highestRow; ++$row) {
    $col = 1;
    $cell = $worksheet->getCellByColumnAndRow($col, $row);
    // Skip empty cells
    while (in_array($cell->getValue(), [null, ''], true)) {
        $col++;
        $cell = $worksheet->getCellByColumnAndRow($col, $row);
    }
    $maxCol = $col + 1;
    for ( ; $col <= $maxCol; ++$col) { 
        $value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
        $rows[$row][$col] = $value;
    }
}
stollr
  • 6,534
  • 4
  • 43
  • 59