Suc*_*Man 4 excel laravel laravel-excel laravel-5.6
我从这里得到教程:https : //laravel-excel.maatwebsite.nl/docs/3.0/export/basics
<?php
...
use App\Exports\ItemsDetailsExport;
class ItemController extends Controller
{
...
public function exportToExcel(ItemsDetailsExport $exporter, $id)
{
//dd($id); I get the result
return $exporter->download('Summary Detail.xlsx');
}
}
Run Code Online (Sandbox Code Playgroud)
我的出口是这样的:
<?php
namespace App\Exports;
use App\Repositories\Backend\ItemDetailRepository;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Illuminate\Support\Facades\Input;
class ItemsDetailsExport implements FromCollection
{
use Exportable;
protected $itemDetailRepository;
public function __construct(ItemDetailRepository $itemDetailRepository)
{
$this->itemDetailRepository = $itemDetailRepository;
}
public function collection()
{
$test = Input::get('id');
dd('yeah', $test);
}
}
Run Code Online (Sandbox Code Playgroud)
我想将 id 参数传递给导出文件。我这样尝试,但我没有得到 id。id 为空
我怎么解决这个问题?
不幸的是,当你有一个特定的参数时,你不能使用普通的依赖注入。这是你可以做的:
class ItemsDetailsExport implements FromCollection
{
use Exportable;
protected $itemDetailRepository;
protected $id;
public function __construct(ItemDetailRepository $itemDetailRepository, $id)
{
$this->itemDetailRepository = $itemDetailRepository;
$this->id = $id;
}
public function collection()
{
$test = $this->id;
dd('yeah', $test);
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是容器不知道如何解析 $id 但是有两种方法可以解决这个问题。
手动传递$id:
public function exportToExcel($id)
{
$exporter = app()->makeWith(ItemsDetailsExport::class, compact('id'));
return $exporter->download('Summary Detail.xlsx');
}
Run Code Online (Sandbox Code Playgroud)路由注入:
将您的路线定义为:
Route::get('/path/to/export/{itemExport}', 'ItemController@exportToExcel');
Run Code Online (Sandbox Code Playgroud)
在您的RouteServiceProvider.php:
public function boot() {
parent::boot();
//Bindings
Route::bind('itemExport', function ($id) { //itemExport must match the {itemExport} name in the route definition
return app()->makeWith(ItemsDetailsExport::class, compact('id'));
});
}
Run Code Online (Sandbox Code Playgroud)
那么你的路由方法被简化为:
public function exportToExcel(ItemsDetailsExport $itemExport)
{
//It will be injected based on the parameter you pass to the route
return $itemExport->download('Summary Detail.xlsx');
}
Run Code Online (Sandbox Code Playgroud)
小智 6
为了将数据从控制器传递到 laravel excel 函数,我们可以传递和使用如下数据
例如,我们必须传递像2019 年这样的数据年,我们将传递如下
在控制器中
Excel::download(new UsersExport(2019), 'users.xlsx');
Run Code Online (Sandbox Code Playgroud)
在 Laravel 导入文件中
class UsersExport implements FromCollection {
private $year;
public function __construct(int $year)
{
$this->year = $year;
}
public function collection()
{
return Users::whereYear('created_at', $this->year)->get();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以参考以下所有官方文档链接
https://docs.laravel-excel.com/3.1/architecture/objects.html#plain-old-php-object
| 归档时间: |
|
| 查看次数: |
12272 次 |
| 最近记录: |