PHPackages                             datasuite/laravel-exporter - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [PDF &amp; Document Generation](/categories/documents)
4. /
5. datasuite/laravel-exporter

ActiveLibrary[PDF &amp; Document Generation](/categories/documents)

datasuite/laravel-exporter
==========================

A fluent, memory-efficient data export package for Laravel supporting CSV, Excel, and JSON formats

v1.0.1(3mo ago)021MITPHPPHP ^8.1CI passing

Since Jan 27Pushed 3mo agoCompare

[ Source](https://github.com/tusharsawant2427/laravel-exporter)[ Packagist](https://packagist.org/packages/datasuite/laravel-exporter)[ RSS](/packages/datasuite-laravel-exporter/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (6)Versions (3)Used By (0)

Laravel Exporter
================

[](#laravel-exporter)

A fluent, memory-efficient data export package for Laravel supporting CSV, Excel, and JSON formats with rich formatting capabilities.

Features
--------

[](#features)

- 🚀 **Fluent API** - Clean, chainable methods for building exports
- 💾 **Memory Efficient** - Uses generators and chunking for large datasets
- 📊 **Multiple Formats** - CSV, Excel (XLSX/XML), and JSON support
- 🔄 **Flexible Data Sources** - Works with Eloquent queries, Collections, and arrays
- 🎯 **Column Types** - Amount, Date, Percentage, Quantity with proper formatting
- 🌍 **Multi-Locale Support** - Configurable number formats for any country (US, UK, EU, India, Japan, China, etc.)
- 🎨 **Conditional Coloring** - Configurable colors for positive/negative amounts (optional)
- 📋 **Report Headers** - Company name, title, date range, generated by (optional)
- ➕ **Totals &amp; Subtotals** - Automatic calculation of column totals (optional)
- 🔧 **Customizable** - Transform rows, set headers, and configure format options
- 📦 **Zero Dependencies** - Excel export works without external libraries (optional OpenSpout support)

Installation
------------

[](#installation)

```
composer require datasuite/laravel-exporter
```

The package will automatically register its service provider via Laravel's package auto-discovery.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

```
php artisan vendor:publish --tag=exporter-config
```

Basic Usage
-----------

[](#basic-usage)

### Using the Facade

[](#using-the-facade)

```
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');
```

### Using the Class Directly

[](#using-the-class-directly)

```
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'));
```

Data Sources
------------

[](#data-sources)

The exporter supports multiple data sources:

```
// 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());
```

Export Formats
--------------

[](#export-formats)

### CSV Export

[](#csv-export)

```
Exporter::make()
    ->format('csv')
    ->options([
        'delimiter' => ',',
        'enclosure' => '"',
        'include_headers' => true,
        'add_bom' => true, // Excel compatibility
    ])
    ->from($data)
    ->toFile('export.csv');
```

### Excel Export

[](#excel-export)

```
Exporter::make()
    ->format('xlsx')
    ->options([
        'sheet_name' => 'Users',
        'include_headers' => true,
    ])
    ->from($data)
    ->toFile('export.xlsx');
```

> **Note:** For native XLSX support, install OpenSpout: `composer require openspout/openspout`Without OpenSpout, exports will use Excel-compatible XML format.

### Excel Export with Column Types

[](#excel-export-with-column-types)

Define column types for proper formatting and optional conditional coloring:

```
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');
```

### Column Types Available

[](#column-types-available)

TypeMethodDescriptionExcel FormatString`->string()`Plain textGeneralInteger`->integer()`Whole numbers\#,##0Amount`->amount()`Currency with optional conditional coloring\#,##0.00 (locale-based)Amount Plain`->amountPlain()`Currency without coloring\#,##0.00Percentage`->percentage()`Percentage values0.00%Date`->date()`Date valuesDD-MMM-YYYYDateTime`->datetime()`Date and timeDD-MMM-YYYY HH:MM:SSBoolean`->boolean()`Yes/No valuesGeneralQuantity`->quantity()`Numeric quantities\#,##0.00### Report Headers (Optional)

[](#report-headers-optional)

Add professional headers to your exports when needed:

```
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');
```

### Totals Row (Optional)

[](#totals-row-optional)

Automatically calculate and add totals when needed:

```
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');
```

### Multi-Locale Support &amp; Conditional Coloring

[](#multi-locale-support--conditional-coloring)

Configure locale-specific number formatting for any country:

```
// 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');
```

#### Supported Locales (Configurable)

[](#supported-locales-configurable)

LocaleCountryNumber FormatCurrency`en_US`United States1,234,567.00$`en_GB`United Kingdom1,234,567.00£`en_IN`India12,34,567.00₹`de_DE`Germany1.234.567,00€`fr_FR`France1 234 567,00€`ja_JP`Japan1,234,567¥`zh_CN`China1,234,567.00¥Add more locales in `config/exporter.php`.

### JSON Export

[](#json-export)

```
Exporter::make()
    ->format('json')
    ->options([
        'pretty_print' => true,
        'wrap_in_object' => true,
        'data_key' => 'users',
        'include_metadata' => true,
    ])
    ->from($data)
    ->toFile('export.json');
```

Column Selection
----------------

[](#column-selection)

### Simple Columns

[](#simple-columns)

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

### Column Aliases

[](#column-aliases)

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

### Nested Columns (Dot Notation)

[](#nested-columns-dot-notation)

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

Custom Headers
--------------

[](#custom-headers)

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

Row Transformation
------------------

[](#row-transformation)

Transform each row before export:

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

Output Methods
--------------

[](#output-methods)

### Save to File

[](#save-to-file)

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

### Download Response

[](#download-response)

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

### Stream Response (Memory Efficient)

[](#stream-response-memory-efficient)

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

### Get as String

[](#get-as-string)

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

Using the Exportable Trait
--------------------------

[](#using-the-exportable-trait)

Add export functionality directly to your models:

```
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'];
}
```

Then use it like this:

```
// 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'));
```

Controller Example
------------------

[](#controller-example)

```
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}");
    }
}
```

Memory Optimization
-------------------

[](#memory-optimization)

For large datasets, the package automatically uses:

- **Generators** - Data is processed one row at a time
- **Lazy Collections** - Eloquent queries use `lazy()` for memory efficiency
- **Chunking** - Configure chunk size for optimal performance

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

Configuration
-------------

[](#configuration)

Publish the config file to customize defaults:

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

    'csv' => [
        'delimiter' => ',',
        'enclosure' => '"',
        'include_headers' => true,
        'add_bom' => true,
    ],

    'excel' => [
        'include_headers' => true,
        'sheet_name' => 'Sheet1',
    ],

    'json' => [
        'pretty_print' => false,
        'wrap_in_object' => false,
    ],
];
```

Requirements
------------

[](#requirements)

- PHP 8.1+
- Laravel 10.x or 11.x

Optional Dependencies
---------------------

[](#optional-dependencies)

- `openspout/openspout` - For native XLSX file support
- `phpoffice/phpspreadsheet` - For advanced Excel features (formulas, conditional formatting, cell merging)

Maatwebsite Excel-Style Exports (NEW!)
--------------------------------------

[](#maatwebsite-excel-style-exports-new)

If you're familiar with [Maatwebsite Excel](https://laravel-excel.com/), you'll feel right at home! We now support the same interface-based **Concerns** pattern for cleaner, reusable export classes.

### Quick Start

[](#quick-start)

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

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

### Creating an Export Class

[](#creating-an-export-class)

#### Simple Export (FromCollection)

[](#simple-export-fromcollection)

```
