如何在 PhpSpreadsheet 中获取第一列索引
How to get first column index in PhpSpreadsheet
我必须遍历 xls 文档前两列的所有行。
问题是该特定文档的第一列是 "G",索引为 7。
有没有办法获取第一列索引,因为我不想对其进行硬编码。
我的循环:
$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;
}
}
您可以添加一个 while 循环来跳过空单元格。试试这个:
$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;
}
}
我必须遍历 xls 文档前两列的所有行。 问题是该特定文档的第一列是 "G",索引为 7。
有没有办法获取第一列索引,因为我不想对其进行硬编码。
我的循环:
$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;
}
}
您可以添加一个 while 循环来跳过空单元格。试试这个:
$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;
}
}