Laravel导入xls/xlsx到MySQL报Undefined offset:1错误如何解决?
问题原因
Undefined offset: 1 报错的核心原因有三点:
- 多Sheet处理逻辑写法错误:你在
jurusanImport主类中同时使用了WithConditionalSheets多Sheet处理和ToModel接口,但是按照Maatwebsite Excel的设计规范,多Sheet场景下,每个Sheet对应的独立Import类才需要实现ToModel接口,主类的model()方法不会被实际调用,你实际执行的导入逻辑和你写的model()代码不匹配。 - 未跳过表头行:你上传的Excel第一行是字段表头,没有配置跳过的话,表头行会被当成普通数据解析,虽然不会直接报错,但会导致无效数据入库。
- xls/xlsx格式空行解析规则和CSV不同:xls/xlsx会将所有带格式的空行也解析为长度不足的数组,当数组没有索引1时就会触发报错,CSV不会出现这个问题是因为CSV的空行解析逻辑不会读取无内容的行。
解决方法
你可以根据是否需要多Sheet导入选择对应方案:
方案1:不需要多Sheet导入(仅导入Worksheet 1,推荐)
直接简化jurusanImport.php代码,移除多Sheet相关逻辑,添加跳表头和空行校验:
use App\jurusan; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithStartRow; class jurusanImport implements ToModel, WithStartRow { /** * 指定从第二行开始读取,跳过表头 */ public function startRow(): int { return 2; } public function model(array $row) { // 校验行数据是否完整,空行直接跳过不处理 if (!isset($row[1], $row[2])) { return null; } return new jurusan([ 'nama_jurusan' => $row[1], 'deskripsi' => $row[2], ]); } }
方案2:需要多Sheet导入
保留多Sheet配置,单独为每个Sheet创建对应的Import类,将数据处理逻辑放到对应Sheet的类中:
- 修正
jurusanImport.php主类代码,仅保留多Sheet路由逻辑:
use Maatwebsite\Excel\Concerns\WithMultipleSheets; use Maatwebsite\Excel\Concerns\WithConditionalSheets; class jurusanImport implements WithMultipleSheets { use WithConditionalSheets; public function conditionalSheets(): array { return [ 'Worksheet 1' => new FirstSheetImport(), 'Worksheet 2' => new SecondSheetImport(), 'Worksheet 3' => new ThirdSheetImport(), ]; } }
- 新建
FirstSheetImport.php(路径和jurusanImport.php一致),编写对应Sheet的处理逻辑:
use App\jurusan; use Maatwebsite\Excel\Concerns\ToModel; use Maatwebsite\Excel\Concerns\WithStartRow; class FirstSheetImport implements ToModel, WithStartRow { public function startRow(): int { return 2; } public function model(array $row) { if (!isset($row[1], $row[2])) { return null; } return new jurusan([ 'nama_jurusan' => $row[1], 'deskripsi' => $row[2], ]); } }
- 同理编写
SecondSheetImport.php、ThirdSheetImport.php的对应逻辑即可。
修改完成后重新导入即可解决xls/xlsx格式的报错问题,数据库存量数据不会影响导入逻辑,无需额外处理。
内容的提问来源于stack exchange,提问作者TheBetweener
相关产品推荐
相关产品推荐

