相关文章推荐
憨厚的冲锋衣  ·  OPPO Reno14 Pro ...·  3 天前    · 
侠义非凡的课本  ·  NVDA 更新日志·  3 天前    · 
曾经爱过的松树  ·  DevExpress Universal ...·  3 天前    · 
潇洒的山楂  ·  Uncaught ...·  2 天前    · 
文雅的领结  ·  重用的undo日志 ...·  2 年前    · 
逃跑的键盘  ·  RapidJSON —— C++ 快速 ...·  2 年前    · 

https://docs.laravel-excel.com/3.1/getting-started

git地址

https://github.com/maatwebsite/Laravel-Excel

在业务中会经常遇到需要导入导出Excel的需求,在使用laravel项目的时候,可以引入 maatwebsite/Excel 包,简单的实现这个功能。

我使用的是Laravel 6.0 ,截止目前兼容的 maatwebsite/excel 版本为3.1 ,所以不需要指定版本,推荐使用Composer安装:

composer require maatwebsite/excel

如果要指定版本,可以使用以下命令安装:

composer require maatwebsite/excel ~3.1

Laravel与maatwebsite/excel版本的对应关系见下表:

Version Laravel Version PHP Version

使用命令发布配置文件,会在config文件夹下生成excel.php

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

导入Excel

我封装了一个类,可以将Excel导入成一个二维数组

namespace App\Utils; use Maatwebsite\Excel\Facades\Excel; class UploadHelper public static function uploadExcel ($file){ if($file->isValid()){ $vailExtension = ['xlsx','xls']; if(! in_array($file->getClientOriginalExtension() ,$vailExtension) ){ throw new \Exception("文件格式错误"); return Excel::toArray(new Import, $file)[0]; }else{ throw new \Exception("文件无效");

直接静态调用即可

namespace App\Http\Controllers; use App\Utils\UploadHelper; use Illuminate\Http\Request; use Illuminate\Http\Request; class Demo public function importDemo (Request $request){ $isFile = $request->hasFile('file'); if (!$isFile) { throw new \Exception("请上传文件"); $data = UploadHelper::uploadExcel($request->file('file')); dd($data);

导出Excel

创建文件Export.php,并将下面的内容粘进去

namespace App\Utils; use Maatwebsite\Excel\Concerns\FromCollection; class Export implements FromCollection private $row; private $data; public function __construct($row,$data) $this->row = $row; $this->data = $data; * @return \Illuminate\Support\Collection public function collection() $row = $this->row; $data = $this->data; //设置表头 foreach ($row[0] as $key => $value) { $key_arr[] = $key; //输入数据 foreach ($data as $key => &$value) { $js = []; for ($i=0; $i < count($key_arr); $i++) { $js = array_merge($js,[ $key_arr[$i] => $value[ $key_arr[$i] ] ?? '' ]); array_push($row, $js); unset($value); return collect($row); namespace App\Http\Controllers; use App\Utils\Export; use Maatwebsite\Excel\Facades\Excel; class Demo public function exportDemo(){ $fileName = 'excel_name.xlsx'; //将生成的Excel保存到本地,在服务器端使用时注意要给文件夹权限 $row[] = [ "name" => "姓名", "sex" => "性别", $list = [ 'name' => '张三', 'sex' => '男' 'name' => '李四', 'sex' => '女' 'name' => '老王', 'sex' => '男' Excel::store(new Export($row,$list),$fileName ,"public"); $path = "/storage/{$fileName}"; //直接触发下载 //Excel::download(new Export($row,$list),$fileName ,"public");

如果导出的字段包含长数字,出现科学计数法的情况,请移步 Laravel 使用 maatwebsite/excel 时长数字出现科学计数法的解决办法