1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace app\common\util;
- use PhpOffice\PhpSpreadsheet\Exception;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
- class PhpSpreadsheetImport
- {
-
- public static function readData(string $path, array $field = [], int $row = 2, int $sheetIndex = 0, string $scene = 'excel'): array
- {
- try {
-
- $reader = IOFactory::createReader('Xlsx');
-
- $reader->setReadDataOnly(true);
-
- $spreadsheet = $reader->load($path);
-
- $sheet = $spreadsheet->getSheet($sheetIndex);
-
- return self::getCellData($row, $sheet, $field);
- } catch (\Exception $e) {
-
- return ['code' => $e->getCode(), 'errMsg' => $e->getMessage()];
- }
- }
-
- private static function getCellData($row, object $sheet, array $field):array
- {
-
- $highestColumn = $sheet->getHighestColumn();
-
- $highestRow = $sheet->getHighestRow();
-
- $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
- $data = [];
-
- for ($row; $row <= $highestRow; $row++) {
- $build = [];
-
- for ($col = 1; $col <= $highestColumnIndex; $col++) {
-
-
- $chr = chr(64 + $col);
-
- $key = $field[$chr] ?? $chr;
-
- $build[$key] = $sheet->getCellByColumnAndRow($col, $row)->getValue();
- }
- $data[] = $build;
- }
- return $data;
- }
- }
|