PhpSpreadsheet - 获取行而不在每个单元格上进行迭代

时间:2018-04-01 09:47:40

标签: phpexcel phpspreadsheet

我正在使用PhpSpreadsheet轻松读取xls文档并在进行一些计算后插入到数据库中。我成功地使用了文档中的示例,但我发现它太复杂了,我确信我错过了一些东西,而且可以更轻松地完成。

$worksheet = $this->getWorksheet("file.xls");
foreach ($worksheet->getRowIterator() as $row) {
  $cellIterator = $row->getCellIterator();
  $cellIterator->setIterateOnlyExistingCells(FALSE);
  foreach ($cellIterator as $key => $cell) {
    $cellValue = $cell->getValue();

    if($key == 'A')
      $field1 = $cellValue;
    if($key == 'B') {
      $dateTime = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue);
      $date = $dateTime->format("Y-m-d");
    }
    if($key == 'C')
      $field2 = $cellValue;
    if($key == 'D')
      $field3 = $cellValue;
    if($key == 'E')
      $field4 = $cellValue;
  }
}

我原本期望$row->getCell("A")->getValue()之类的东西可用。

所以......我错过了什么吗?

3 个答案:

答案 0 :(得分:3)

希望这会有所帮助

$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5
for ($row = 1; $row <= $highestRow; ++$row) {
    for ($col = 1; $col <= $highestColumnIndex; ++$col) {
        $value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
    }
}    

答案 1 :(得分:0)

有关直接按列和行获取值的信息,请参阅docs,而不是测试密钥

来自示例:

// Get the value from cell B5
$cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(2, 5)->getValue();

希望有所帮助

答案 2 :(得分:0)

这是我发现的东西

        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        $spreadsheet = $reader->load("test.xlsx");
        $sheet = $spreadsheet->getSheet(0);

        $nb = 0;

        foreach ($sheet->getRowIterator() as $row) {

            echo $sheet->getCell("A$nb")->getValue();
            echo "<hr>";
            
            $nb++;
        }