laravel 10+/php 8.1+ 必须用 maatwebsite/excel:^4.0,装错版本会报 class not found 或 bindshared 错误;需 composer remove 后重装,改用 illuminate\support\facades\excel,import() 第二参数必须为字符串路径,非 uploadedfile;加 withchunkreading、withskippedemptyrows 和 withencoding('utf-8') 处理大文件、空行与乱码;表头统一小写处理,禁用 cache 防 “undefined array key 'type'” 错误。

直接用 maatwebsite/excel 包是最可行的路径,但 Laravel 10+ 和 PHP 8.1+ 下,90% 的失败不是代码写错,而是版本没对齐、路径拼错或接口调用方式过时。
装哪个版本?Laravel 10/11 必须用 maatwebsite/excel:^4.0
装错就报 Class "Maatwebsite\Excel\ExcelServiceProvider" not found 或 Call to undefined method bindShared()——这是底层依赖断了,不是你漏了配置。
- 先清干净:
composer remove maatwebsite/excel - 再重装指定版本:
composer require maatwebsite/excel:^4.0 phpoffice/phpspreadsheet:^2.0 - v4 已弃用
Excel门面,全部改用Illuminate\Support\Facades\Excel - 如果服务提供者没自动注册(比如禁用了自动发现),才手动加
Maatwebsite\Excel\ExcelServiceProvider::class到config/app.php的providers数组里
Excel::import() 报 File not found?检查路径是不是字符串
Excel::import(new UsersImport, $request->file('import')) 是典型错误:它传的是 UploadedFile 实例,而 import() 第二个参数必须是文件路径字符串或 SplFileInfo。
- 正确做法:先存到 storage:
$path = $request->file('import')->store('imports') - 再拼完整路径:
storage_path('app/' . $path)—— 漏掉storage_path('app/')这层,绝对报错 - 导入完可选删临时文件:
Storage::delete($path) - 前端表单记得加
accept=".xlsx,.csv",避免上传 .xls 触发PhpSpreadsheet\Exception
导入空、乱码、内存爆?加这三接口就够了
默认 ToModel 会把整张表读进内存,10 万行 Excel 很容易 Allowed memory size exhausted;Windows 下中文常变 ????;空行还会让 model() 创建空模型报错。
- 加
WithChunkReading接口,实现chunkSize()返回500~1000 - 加
WithSkippedEmptyRows跳过全空行 - 链式调用
->withEncoding('UTF-8')(仅 v4 支持)解决中文乱码 - 别信“自动识别编码”,
withEncoding()是唯一可控手段
表头映射总失败?别依赖 WithHeadingRow 自动转键名
PhpSpreadsheet 默认把表头转小写、去空格、去点号,$row['User Name'] 实际变成 $row['username'];首行有合并单元格时,列索引直接错位。
- 保险做法:
$row = array_change_key_case($row, CASE_LOWER)放在model()开头 - 合并表头?改用
headingRow()返回0,再手动定义字段映射数组 - 列名含空格或点号?放弃
WithHeadingRow,改用toArray()+ 数字索引:$row[0]、$row[1] - 日期列必须用
PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject()转,不能直接 cast
最常被忽略的其实是缓存配置——Undefined array key "type" 错误实际来自 phpspreadsheet 读取缓存驱动时的键名变更,得去 config/excel.php 里检查 cache 配置项是否还沿用旧版结构。











