Laravel 使用 maatwebsite/Excel 3.1 实现导入导出的简单方法
官方文档
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 |
---|---|---|
2.1 | <=5.6 | <=7.0 |
3.0 | ^5.5 | ^7.0 |
3.1 | ^5.8 ^6.0 ^7.0 ^8.0 | ^7.2 ^8.0 |
Laravel5.5以上的包是自动注册的。如果要发布配置文件,可以执行下面的命令:
配置
使用命令发布配置文件,会在config文件夹下生成excel.php
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
导入Excel
我封装了一个类,可以将Excel导入成一个二维数组
<?php
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("文件无效");
}
}
}
直接静态调用即可
<?php
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,并将下面的内容粘进去
<?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);
}
}
调用方法
<?php
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");
}
}
如果导出的字段包含长数字,出现科学计数法的情况,请移步