netsells / exportable
启用以PDF或CSV格式导出类数据
Requires
- dompdf/dompdf: ^0.8.2
- netsells/csvme: ^1.1
This package is auto-updated.
Last update: 2024-09-07 17:13:42 UTC
README
允许轻松从Eloquent模型导出数据
它由Netsells团队创建和维护
入门
使用Composer安装Exportable。
$ composer require netsells/exportable
实现
此Exportable实现使从Eloquent模型到CSV或PDF格式的数据导出变得简单。只需扩展包中包含的Netsells\Exportable\ExportableModel基类,即可为任何需要使用导出功能的Eloquent模型使用。
use Netsells\Exportable\ExportableModel;
class User extends ExportableModel
ExportableModel
可导出模型的基类实现了并满足可以应用于其他类的ExportableContract接口。执行数据导出的两个特质也在此导入。
use Netsells\Exportable\Contracts\ExportableContract;
use Netsells\Exportable\Traits\ExportableCsv;
use Netsells\Exportable\Traits\ExportablePdf;
class ExportableModel extends Model implements ExportableContract
{
use ExportablePdf;
use ExportableCsv;
导出数据的核心方法如下
public static function exportToPdf
public static function exportToCsv
类中的其余两个方法用于构建用于导出数据到CSV格式和检索常量(如果它们用于提供配置或视图的路线)的布局闭包。
public static function getLayoutClosure
public static function getConstant
基本用法
将数据导出为PDF格式需要用于格式输出的视图、要导出的数据和表头列表。包中包含一个示例视图,并且可以轻松地应用自定义视图。
$users = User::all()->toArray(); $headers = [ "first_name" => "First Name", "last_name" => "Last Name", "email" => "Email", "phone" => "Phone", ]; $view = "exportable\\pdf"; User::exportToPdf($view, $users, $headers);
CSV
将数据导出为CSV格式只需数据和(如果需要)输出所需的表头。由于它是CSV,因此无需特殊格式。
$users = User::all()->toArray(); $headers = [ "first_name" => "First Name", "last_name" => "Last Name", "email" => "Email", "phone" => "Phone", ]; User::exportToCsv($users, $headers);
高级用法
包中包含一个名为exportable.php的文件,其中包含用于设置可以用于设置导出到CSV或PDF格式的数据的骨架。可以根据要求对其进行修改,具有多个部分用于不同的导出。
return [ 'pdf' => [ 'headers' => [ // Map headers for PDF export here ], // View used to construct PDF export 'view' => 'exportable\pdf', ], 'csv' => [ 'headers' => [ // Map headers for CSV export here ], ] ];
示例
return [ 'user' => [ 'pdf' => [ 'headers' => [ "first_name" => "First Name", "last_name" => "Last Name", "email" => "Email", "phone" => "Phone", "email" => "Email", ], // View used to construct PDF export 'view' => 'exportable\user_pdf', ], ], 'admin' => [ 'pdf' => [ 'headers' => [ "first_name" => "First Name", "last_name" => "Last Name", "email" => "Email", "phone" => "Phone", "email" => "Email", "permission_level" => "Permissions", ], // View used to construct PDF export 'view' => 'exportable\admin_pdf', ], ] ];
为了简单起见,可以在模型中将每个配置的路径添加为常量。
class User extends ExportableModel { const ADMIN_PDF_CONFIG = 'exportable.admin.pdf'; const USER_PDF_CONFIG = 'exportable.user.pdf';
使用getConstant静态方法,可以检索常量的值。如果类中没有找到常量,此方法返回null。使用常量的值,可以使用以下示例所示所需配置数据来导出数据。
// Confirm class constant defined if ($configPath = User::getConstant('ADMIN_PDF_CONFIG')) { $config = Config::get($configPath); $headers = $config['headers']; $view = $config['view']; $users = User::all()->toArray(); User::exportToPdf($view, $data, $headers); }
构建
许可证
本项目采用MIT许可证 - 有关详细信息,请参阅LICENSE.md文件