官方文檔
https://docs.laravel-excel.com/3.1/getting-startedgit地址
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");
}
}
如果導出的字段包含長數字,出現科學計數法的情況,請移步Laravel 使用 maatwebsite/excel 時長數字出現科學計數法的解決辦法
