Created
March 8, 2019 22:02
-
-
Save odan/18a6be156a8476d12a89354f7e46a66e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use PhpOffice\PhpSpreadsheet\Cell\Coordinate; | |
use PhpOffice\PhpSpreadsheet\Reader\Xlsx; | |
/** | |
* ExcelFileReader. | |
*/ | |
class ExcelFileReader | |
{ | |
/** | |
* Load excel worksheet and return all values as array. | |
* | |
* @param string $fileName filename | |
* | |
* @return array Values | |
*/ | |
public function loadAll(string $fileName): array | |
{ | |
$reader = new Xlsx(); | |
$reader->setReadDataOnly(true); | |
$excel = $reader->load($fileName); | |
$worksheet = $excel->getActiveSheet(); | |
$highestRow = $worksheet->getHighestRow(); | |
$highestColumn = $worksheet->getHighestColumn(); | |
$highestColumnIndex = Coordinate::columnIndexFromString($highestColumn); | |
$rows = []; | |
for ($row = 1; $row <= $highestRow; $row++) { | |
for ($col = 1; $col <= $highestColumnIndex; $col++) { | |
$cell = $worksheet->getCellByColumnAndRow($col, $row); | |
$rows[$row][$col] = $cell !== null ? $cell->getValue() : null; | |
} | |
} | |
$result = []; | |
if (empty($rows)) { | |
return []; | |
} | |
// Remove first row (field titles) and extract field names | |
$fields = array_splice($rows, 0, 1); | |
$fields = $fields[0]; | |
$unknownField = 1; | |
foreach ($fields as $index => $field) { | |
if (!isset($field)) { | |
$fields[$index] = 'unknown_' . $unknownField++; | |
} | |
} | |
// Copy values to field names | |
foreach ($rows as $rowNumber => $row) { | |
foreach ($row as $index => $value) { | |
if (!isset($fields[$index])) { | |
continue; | |
} | |
$name = $fields[$index]; | |
$result[$rowNumber][$name] = $value; | |
} | |
} | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment