【问题标题】:How to get first column index in PhpSpreadsheet如何在 PhpSpreadsheet 中获取第一列索引
【发布时间】:2019-10-01 15:20:18
【问题描述】:

我必须遍历 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;
    }
}

【问题讨论】:

  • G 不是“第一列”。它可能是您感兴趣的数据的第一列,但A 是第一列。如果前 6 列是空的,您可以遍历这些列,直到到达第一个非空列并假设那是您的第一列。根据您对情况的描述,我认为使用硬编码列可能更安全。

标签: php excel spreadsheet phpspreadsheet


【解决方案1】:

您可以添加一个 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;
    }
}

【讨论】:

    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 2012-05-30
    • 2019-05-11
    • 1970-01-01
    • 2012-02-22
    • 2015-09-11
    • 1970-01-01
    • 2017-01-15
    相关资源
    最近更新 更多