悠悠楠杉
Laravel数据导出实战:从Excel到PDF的完整实现方案
12/19
正文:
在企业管理后台开发中,数据导出是高频需求。不同于简单的数据库转储,业务场景往往要求带格式的报表输出。以下是经过实战验证的Laravel数据导出方案:
一、Excel导出:使用Laravel-Excel扩展包
这是目前最成熟的解决方案,底层依赖PHPOffice/PhpSpreadsheet。首先安装扩展包:
composer require maatwebsite/excel创建导出类(示例导出用户数据):
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::select('name','email','created_at')
->where('active', true)
->orderBy('created_at', 'desc')
->get();
}
}控制器调用方式:
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}高级功能支持:
- 自定义表头(实现WithHeadings接口)
- 单元格样式控制(WithStyles接口)
- 大数据量分块处理(FromQuery配合WithChunkReading)
二、PDF导出:TCPDF与Dompdf双方案
方案A:TCPDF(适合复杂报表)
安装TCPDF适配包:
composer require elibyy/tcpdf-laravel生成带中文的PDF示例:
public function generatePdf()
{
$pdf = new \TCPDF();
$pdf->AddPage();
$pdf->SetFont('stsongstdlight', '', 14);
$pdf->Write(10, '销售报表 '.date('Y-m-d'));
$pdf->Output('report.pdf');
}方案B:Dompdf(适合HTML转PDF)
composer require barryvdh/laravel-dompdfBlade模板转PDF:
public function invoicePdf($id)
{
$data = Order::find($id);
$pdf = PDF::loadView('invoices.template', compact('data'));
return $pdf->download('invoice.pdf');
}三、原生CSV导出(轻量级方案)
对于简单数据导出,可直接使用Laravel响应:
public function exportCsv()
{
$headers = [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="products.csv"',
];
$callback = function() {
$products = Product::all();
$file = fopen('php://output', 'w');
fputcsv($file, ['ID', '名称', '价格']);
foreach ($products as $p) {
fputcsv($file, [$p->id, $p->name, $p->price]);
}
fclose($file);
};
return response()->stream($callback, 200, $headers);
}性能优化要点
大数据导出务必使用队列处理:
php Excel::store(new LargeExport(), 'large-file.xlsx', 's3')->chain([ new NotifyAdmin('Export completed') ]);内存控制技巧:
- 对于10万+数据,启用WithChunkReading
- 设置PHP内存限制:iniset('memorylimit', '512M')
- 文件存储策略:
- 临时文件使用S3或OSS云存储
- 本地存储建议定期清理任务
实际项目中,建议将导出功能封装为独立Service类,方便统一处理异常和日志记录。例如创建ExportService处理格式转换、文件名生成等通用逻辑。
