安装
$ composer require maatwebsite/excel
创建配置文件
> php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
简单导出导入不需要做任何配置,继续往下即可.
导出
运行命令
> php artisan make:export TablesExport --model=Table
此命令将在 app
文件夹下面创建Exports\TablesExport.php
类.
填充代码如下:
<?php
namespace App\Exports;
use App\Table;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class TablesExport implements FromCollection,WithHeadings
{
public function collection()
{
return Table::all();
}
//设置导出表头,如果不需要可以不设置.
public function headings():array
{
return[
'ID',
'姓名',
'交易笔数',
'交易金额',
'激活时间',
'机身号',
'入网机型',
'手机号',
'状态',
'创建时间',
'更新时间',
];
}
}
控制器写法
[建路由,建控制器写方法]
namespace App\Http\Controllers\Admin\System;
use App\Table;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Exports\TablesExport;
use App\Imports\TablesImport;
use Maatwebsite\Excel\Facades\Excel;
class TableController extends Controller
{
public function export()
{
return Excel::download(new TablesExport, time().'.xlsx');
}
}
导入
创建导入类
> php artisan make:import TablesImport
此命令将在 app
文件夹下面创建Imports\TablesImport.php
类.
填充代码如下:
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
use App\Table;
class TablesImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return new Table([
'name' => $row['姓名'],
'frequency' => $row['交易笔数'],
'sum' => $row['交易金额'],
'number' => $row['激活时间'],
'integral' => $row['机身号'],
'model' => $row['入网机型'],
'mobile' => $row['手机号'],
'state' => $row['状态'],
]);
}
public function format()
{
HeadingRowFormatter::default(HeadingRowFormatter::FORMATTER_NONE);
return $this;
}
}
控制器方法
public function import($filepath)
{
$import=new TablesImport();
Excel::import($import->format(), $filepath);
}
将文件路径传入方法即可.