如何在Lumen及Laravel Lumen中借助扩展包导出CSV/Excel并构建API
Hey there! Let's break down how to handle CSV exports in Lumen, plus how to build a robust API that can export both CSV and Excel using a trusted package. Let's dive right in:
If you don't want to add extra dependencies, you can export CSV directly using PHP's native functions and Lumen's response system. Here's how:
Step 1: Add a Route
Open your routes/api.php (or routes/web.php depending on your setup) and add a route for the export:
$router->get('/export/csv', 'ExportController@exportCsv');
Step 2: Create the Controller
Generate a new controller (or use an existing one) with the export logic:
<?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Response; class ExportController extends Controller { public function exportCsv() { // Fetch your data (replace with your model/query) $users = User::all(); // Stream the CSV directly to the browser return response()->stream(function() use ($users) { // Open output stream $handle = fopen('php://output', 'w'); // Write CSV headers fputcsv($handle, ['ID', 'Name', 'Email', 'Created At']); // Write data rows foreach ($users as $user) { fputcsv($handle, [ $user->id, $user->name, $user->email, $user->created_at->toDateTimeString() ]); } fclose($handle); }, 200, [ // Set headers to trigger download 'Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="users_' . date('Ymd') . '.csv"' ]); } }
A quick note: php://output is a write-only stream that sends data directly to the browser. fputcsv automatically handles escaping commas and special characters, so you don't have to worry about broken CSV formatting.
For more flexibility (like Excel support, custom formatting, or batch exports), the maatwebsite/excel package is the go-to choice for Laravel/Lumen. Here's how to set it up:
Step 1: Install the Package
Run this command in your project root:
composer require maatwebsite/excel
Step 2: Configure Lumen to Use the Package
Open bootstrap/app.php and:
- Uncomment this line to enable facades (if you haven't already):
$app->withFacades(); - Register the package's service provider:
$app->register(Maatwebsite\Excel\ExcelServiceProvider::class); - Add a facade alias (optional but convenient):
class_alias(Maatwebsite\Excel\Facades\Excel::class, 'Excel');
Step 3: Create an Export Class
Create a new directory app/Exports and add an export class (e.g., UsersExport.php) that defines your export structure:
<?php namespace App\Exports; use App\User; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\WithHeadings; class UsersExport implements FromCollection, WithHeadings { // Define the data to export public function collection() { // Use a select query to fetch only the columns you need return User::select('id', 'name', 'email', 'created_at')->get(); } // Define CSV/Excel headers public function headings(): array { return ['ID', 'Name', 'Email', 'Created At']; } }
Pro tip: You can add more concerns (like WithMapping to transform data, or WithStyles for Excel formatting) to customize the export further.
Step 4: Add the API Route
Add a dynamic route that accepts the export type (csv/xlsx):
$router->get('/export/{type}', 'ExportController@export');
Step 5: Update the Controller with Export Logic
Add this method to your ExportController:
public function export($type) { // Validate the requested export type if (!in_array($type, ['csv', 'xlsx'])) { return response()->json([ 'error' => 'Invalid export type. Please use "csv" or "xlsx".' ], 400); } $filename = 'users_' . date('Ymd') . '.' . $type; // Trigger the download return Excel::download(new \App\Exports\UsersExport(), $filename); }
Now you can hit /export/csv or /export/xlsx to get the corresponding file—no extra code needed for each format!
Bonus: Customize the Package (Optional)
If you need to tweak settings like storage paths or CSV delimiters, you can publish the package config:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Then move the published excel.php file to your config directory (create it if it doesn't exist) and adjust the settings as needed.
内容的提问来源于stack exchange,提问作者Anil Pahelajani

