PHP code example of datasuite / laravel-exporter

1. Go to this page and download the library: Download datasuite/laravel-exporter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

datasuite / laravel-exporter example snippets


use LaravelExporter\Facades\Exporter;

// Export users to CSV
Exporter::make()
    ->from(User::query())
    ->toFile(storage_path('app/exports/users.csv'));

// Export with specific columns
Exporter::make()
    ->columns(['id', 'name', 'email'])
    ->from(User::query())
    ->download('users.csv');

use LaravelExporter\Exporter;

$exporter = Exporter::make()
    ->format('xlsx')
    ->columns(['id', 'name', 'email'])
    ->headers(['ID', 'Full Name', 'Email Address'])
    ->from(User::query())
    ->toFile(storage_path('app/exports/users.xlsx'));

// Eloquent Query Builder
Exporter::make()->from(User::query());
Exporter::make()->from(User::where('active', true));

// Collections
Exporter::make()->from(collect($data));

// Arrays
Exporter::make()->from($arrayOfData);

// LazyCollections (memory efficient)
Exporter::make()->from(User::lazy());

Exporter::make()
    ->format('csv')
    ->options([
        'delimiter' => ',',
        'enclosure' => '"',
        '

Exporter::make()
    ->format('xlsx')
    ->options([
        'sheet_name' => 'Users',
        '

use LaravelExporter\Facades\Exporter;

Exporter::make()
    ->format('xlsx')
    ->columns(fn($cols) => $cols
        ->string('order_number', 'Order #')
        ->date('order_date', 'Date')
        ->string('customer_name', 'Customer')
        ->amount('total_amount', 'Amount')      // Green for +ve, Red for -ve
        ->quantity('items_count', 'Items')
        ->percentage('discount', 'Discount %')
    )
    ->from(Order::query())
    ->download('orders.xlsx');

use LaravelExporter\Support\ReportHeader;

Exporter::make()
    ->format('xlsx')
    ->header(fn($h) => $h
        ->company('Acme Corporation')
        ->title('Sales Report')
        ->subtitle('Monthly Summary')
        ->dateRange('01-Nov-2024', '30-Nov-2024')
        ->generatedBy('John Doe')
        ->generatedAt()
    )
    ->columns(fn($cols) => $cols
        ->string('invoice_no', 'Invoice #')
        ->amount('amount', 'Amount')
    )
    ->from($data)
    ->download('sales-report.xlsx');

Exporter::make()
    ->format('xlsx')
    ->columns(fn($cols) => $cols
        ->string('product', 'Product')
        ->quantity('qty', 'Quantity')
        ->amount('price', 'Price')
        ->amount('total', 'Total')
    )
    ->withTotals(['qty', 'price', 'total'])  // Columns to sum
    ->totalsLabel('GRAND TOTAL')
    ->from($data)
    ->download('products.xlsx');

// US format (default): 1,234,567.00
Exporter::make()
    ->format('xlsx')
    ->locale('en_US')
    ->from($data)
    ->download('report-us.xlsx');

// European format: 1.234.567,00
Exporter::make()
    ->format('xlsx')
    ->locale('de_DE')
    ->from($data)
    ->download('report-de.xlsx');

// Indian format: 12,34,567.00
Exporter::make()
    ->format('xlsx')
    ->locale('en_IN')
    ->from($data)
    ->download('report-in.xlsx');

// With optional conditional coloring (green/red for +ve/-ve)
Exporter::make()
    ->format('xlsx')
    ->locale('en_US')
    ->conditionalColoring(true)    // Optional - enable colored amounts
    ->columns(fn($cols) => $cols
        ->string('account', 'Account')
        ->amount('debit', 'Debit')
        ->amount('credit', 'Credit')
        ->amount('balance', 'Balance')
    )
    ->from($ledgerEntries)
    ->download('ledger.xlsx');

Exporter::make()
    ->format('json')
    ->options([
        'pretty_print' => true,
        'wrap_in_object' => true,
        'data_key' => 'users',
        '

Exporter::make()
    ->columns(['id', 'name', 'email'])
    ->from(User::query());

Exporter::make()
    ->columns([
        'User ID' => 'id',
        'Full Name' => 'name',
        'Email Address' => 'email',
    ])
    ->from(User::query());

Exporter::make()
    ->columns([
        'id',
        'name',
        'department.name', // Access related model
    ])
    ->from(User::with('department'));

Exporter::make()
    ->columns(['id', 'name', 'email'])
    ->headers(['User ID', 'Full Name', 'Email Address'])
    ->from(User::query());

Exporter::make()
    ->transformRow(function (array $row, $originalItem) {
        $row['name'] = strtoupper($row['name']);
        $row['status'] = $originalItem->isActive() ? 'Active' : 'Inactive';
        return $row;
    })
    ->from(User::query());

Exporter::make()
    ->from($data)
    ->toFile(storage_path('app/exports/data.csv'));

return Exporter::make()
    ->from($data)
    ->download('data.csv');

return Exporter::make()
    ->from($data)
    ->stream('data.csv');

$content = Exporter::make()
    ->from($data)
    ->toString();

use LaravelExporter\Traits\Exportable;

class User extends Model
{
    use Exportable;

    // Optional: Define default exportable columns
    protected array $exportable = ['id', 'name', 'email'];

    // Optional: Define default headers
    protected array $exportHeaders = ['ID', 'Full Name', 'Email'];
}

// Export with model defaults
User::query()->export()->toFile('users.csv');

// Export with custom columns
User::where('active', true)
    ->export(['id', 'name'])
    ->download('active-users.csv');

// Quick export all
User::exportAll('csv', storage_path('users.csv'));

use LaravelExporter\Facades\Exporter;

class ExportController extends Controller
{
    public function exportUsers(Request $request)
    {
        $format = $request->get('format', 'csv');

        return Exporter::make()
            ->format($format)
            ->columns(['id', 'name', 'email', 'created_at'])
            ->headers(['ID', 'Name', 'Email', 'Registered At'])
            ->from(User::query())
            ->download("users.{$format}");
    }
}

Exporter::make()
    ->chunkSize(500) // Process 500 rows at a time
    ->from(User::query())
    ->toFile('large-export.csv');

// config/exporter.php
return [
    'default_format' => 'csv',
    'chunk_size' => 1000,

    'csv' => [
        'delimiter' => ',',
        'enclosure' => '"',
        '> false,
        'wrap_in_object' => false,
    ],
];

// Download export
use App\Exports\UsersExport;
use LaravelExporter\Facades\Excel;

return Excel::download(new UsersExport, 'users.xlsx');



namespace App\Exports;

use App\Models\User;
use LaravelExporter\Concerns\FromCollection;
use LaravelExporter\Concerns\WithHeadings;
use LaravelExporter\Concerns\Exportable;

class UsersExport implements FromCollection, WithHeadings
{
    use Exportable;

    public function collection()
    {
        return User::all();
    }

    public function headings(): array
    {
        return ['ID', 'Name', 'Email', 'Created At'];
    }
}



namespace App\Exports;

use App\Models\Product;
use Illuminate\Database\Eloquent\Builder;
use LaravelExporter\Concerns\FromQuery;
use LaravelExporter\Concerns\WithHeadings;
use LaravelExporter\Concerns\WithMapping;
use LaravelExporter\Concerns\ShouldAutoSize;
use LaravelExporter\Concerns\Exportable;

class ProductsExport implements FromQuery, WithHeadings, WithMapping, ShouldAutoSize
{
    use Exportable;

    public function query(): Builder
    {
        return Product::query()->orderBy('category');
    }

    public function headings(): array
    {
        return ['SKU', 'Name', 'Category', 'Price', 'Stock'];
    }

    public function map($product): array
    {
        return [
            $product->sku,
            $product->name,
            $product->category,
            '₹' . number_format($product->price, 2),
            $product->stock_quantity,
        ];
    }
}



namespace App\Exports;

use App\Models\Order;
use Illuminate\Database\Eloquent\Builder;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use LaravelExporter\Concerns\FromQuery;
use LaravelExporter\Concerns\WithHeadings;
use LaravelExporter\Concerns\WithMapping;
use LaravelExporter\Concerns\WithStyles;
use LaravelExporter\Concerns\WithColumnFormatting;
use LaravelExporter\Concerns\WithTotals;
use LaravelExporter\Concerns\WithReportHeader;
use LaravelExporter\Concerns\Exportable;
use LaravelExporter\Support\ReportHeader;

class OrdersExport implements
    FromQuery,
    WithHeadings,
    WithMapping,
    WithStyles,
    WithColumnFormatting,
    WithTotals,
    WithReportHeader
{
    use Exportable;

    public function query(): Builder
    {
        return Order::query()->with('user')->limit(10000);
    }

    public function headings(): array
    {
        return ['Order #', 'Customer', 'Status', 'Total', 'Date'];
    }

    public function map($order): array
    {
        return [
            $order->order_number,
            $order->user->name,
            ucfirst($order->status),
            $order->total,
            $order->created_at->format('Y-m-d'),
        ];
    }

    public function styles(Worksheet $sheet): array
    {
        return [
            1 => ['font' => ['bold' => true]],
            'A' => ['font' => ['bold' => true]],
        ];
    }

    public function columnFormats(): array
    {
        return [
            'D' => NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1,
        ];
    }

    public function totalColumns(): array
    {
        return ['Total'];
    }

    public function totalLabel(): string
    {
        return 'GRAND TOTAL';
    }

    public function reportHeader(): ReportHeader
    {
        return ReportHeader::make()
            ->title('Orders Report')
            ->addLine('Generated: ' . now()->format('d-M-Y'));
    }
}

use LaravelExporter\Concerns\FromQuery;
use LaravelExporter\Concerns\WithChunkReading;
use LaravelExporter\Concerns\Exportable;

class LargeExport implements FromQuery, WithChunkReading
{
    use Exportable;

    public function query(): Builder
    {
        return Order::query();
    }

    public function chunkSize(): int
    {
        return 1000; // Process 1000 rows at a time
    }
}

use App\Exports\UsersExport;

// From within a controller
return (new UsersExport)->download('users.xlsx');

// Or store to disk
(new UsersExport)->store('exports/users.xlsx', 'local');



namespace App\Exports;

use LaravelExporter\Concerns\WithMultipleSheets;
use LaravelExporter\Concerns\Exportable;

class SalesReportExport implements WithMultipleSheets
{
    use Exportable;

    public function sheets(): array
    {
        return [
            'Products' => new ProductsExport(),
            'Orders' => new OrdersExport(),
        ];
    }
}

use LaravelExporter\Facades\Excel;
use App\Imports\UsersImport;

// Import from file
Excel::import(new UsersImport, 'users.xlsx');

// Import from uploaded file
Excel::import(new UsersImport, $request->file('file'));

// Import from storage disk
Excel::import(new UsersImport, 'imports/users.xlsx', 's3');



namespace App\Imports;

use App\Models\User;
use LaravelExporter\Concerns\ToModel;
use LaravelExporter\Concerns\WithHeadingRow;
use LaravelExporter\Concerns\WithValidation;
use LaravelExporter\Concerns\Importable;

class UsersImport implements ToModel, WithHeadingRow, WithValidation
{
    use Importable;

    public function model(array $row): User
    {
        return new User([
            'name' => $row['name'],
            'email' => $row['email'],
            'password' => bcrypt($row['password']),
        ]);
    }

    public function headingRow(): int
    {
        return 1;
    }

    public function rules(): array
    {
        return [
            'name' => '

use LaravelExporter\Concerns\ToModel;
use LaravelExporter\Concerns\WithUpserts;
use LaravelExporter\Concerns\WithBatchInserts;

class ProductsImport implements ToModel, WithUpserts, WithBatchInserts
{
    public function model(array $row): Product
    {
        return new Product([
            'sku' => $row['sku'],
            'name' => $row['name'],
            'price' => $row['price'],
        ]);
    }

    public function uniqueBy(): string
    {
        return 'sku'; // Update if SKU exists
    }

    public function batchSize(): int
    {
        return 500; // Insert 500 at a time
    }
}

use LaravelExporter\Concerns\WithValidation;
use LaravelExporter\Concerns\SkipsOnFailure;
use LaravelExporter\Imports\Failure;

class UsersImport implements ToModel, WithValidation, SkipsOnFailure
{
    protected array $failures = [];

    public function rules(): array
    {
        return ['email' => ');

foreach ($import->getFailures() as $failure) {
    echo "Row {$failure->row()}: " . implode(', ', $failure->errors());
}

use Illuminate\Support\Collection;
use LaravelExporter\Concerns\ToCollection;
use LaravelExporter\Concerns\WithHeadingRow;

class SalesDataImport implements ToCollection, WithHeadingRow
{
    protected array $summary = [];

    public function collection(Collection $collection): void
    {
        $this->summary = [
            'total_rows' => $collection->count(),
            'total_revenue' => $collection->sum('amount'),
            'average_order' => $collection->avg('amount'),
        ];
    }

    public function headingRow(): int
    {
        return 1;
    }

    public function getSummary(): array
    {
        return $this->summary;
    }
}

// Get raw data as array
$rows = Excel::toArray(new UsersImport, 'users.xlsx');

// Get as Collection
$collection = Excel::toCollection(new UsersImport, 'users.xlsx');

use LaravelExporter\Concerns\WithMultipleSheets;

class WorkbookImport implements WithMultipleSheets
{
    public function sheets(): array
    {
        return [
            0 => new UsersImport(),      // First sheet
            1 => new ProductsImport(),   // Second sheet
            // Or by name:
            // 'Users' => new UsersImport(),
        ];
    }
}

use LaravelExporter\Concerns\Importable;

class UsersImport implements ToModel
{
    use Importable;
    // ...
}

// Usage
$import = new UsersImport;
$import->import('users.xlsx');

// Or
$array = $import->toArray('users.xlsx');
$collection = $import->toCollection('users.xlsx');

$result = Excel::import(new UsersImport, 'users.xlsx');

echo "Total rows: " . $result->totalRows();
echo "Imported: " . $result->importedRows();
echo "Skipped: " . $result->skippedRows();
echo "Failed: " . $result->failedRows();
echo "Success rate: " . $result->successRate() . "%";
echo "Duration: " . $result->duration() . "s";
echo "Memory: " . $result->peakMemoryFormatted();

if ($result->errors()->hasFailures()) {
    foreach ($result->errors()->failures() as $failure) {
        // Handle failures
    }
}
bash
php artisan vendor:publish --tag=exporter-config