Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreiTelteu/f57c863393d6ff4ba2362f659dfab36f to your computer and use it in GitHub Desktop.
Save AndreiTelteu/f57c863393d6ff4ba2362f659dfab36f to your computer and use it in GitHub Desktop.
How to export/import in excel format with maatwebsite/excel using inline anonymous class, without any external files #laravel

Using this plugin: maatwebsite/excel

composer require maatwebsite/excel

You can use this anywhere in your app.

<?php
$array = [
    [ 'id' => 1, 'name' => 'john doe', 'email' => 'john.doe@example.com' ],
    [ 'id' => 2, 'name' => 'foe bar', 'email' => 'foe.bar@example.com' ],
];
$columns = ['ID', 'Name', 'Email'];

$export = new class($array, $columns) implements
    \Maatwebsite\Excel\Concerns\FromArray,
    \Maatwebsite\Excel\Concerns\WithHeadings,
    \Maatwebsite\Excel\Concerns\ShouldAutoSize
{
    use \Maatwebsite\Excel\Concerns\Exportable;
    private $array;
    private $columns;
    public function __construct($array, $columns) {
        $this->array = $array;
        $this->columns = $columns;
    }
    public function array(): array {
        return $this->array;
    }
    public function headings(): array {
        return $this->columns;
    }
};

return $export->download(
    'export.xlsx',
    \Maatwebsite\Excel\Excel::XLSX
);
// or you can store it on a disk
return $export->store(
    'user/export.xlsx',
    'public',
    \Maatwebsite\Excel\Excel::XLSX
);

image


Inspired by the official collection macro: /src/Mixins/DownloadCollection.php

$array = [
    [ 'id' => 1, 'name' => 'john doe', 'email' => 'john.doe@example.com' ],
    [ 'id' => 2, 'name' => 'foe bar', 'email' => 'foe.bar@example.com' ],
];
collect($array)->downloadExcel('export.xlsx', \Maatwebsite\Excel\Excel::XLSX, true);

The collection macro is way easier to use but it does not support auto column sizing. image

Using the same plugin you can also do a inline import very easy.

$import = new class implements
  \Maatwebsite\Excel\Concerns\ToCollection,
  \Maatwebsite\Excel\Concerns\WithHeadingRow
{
  use \Maatwebsite\Excel\Concerns\Importable;
  public function collection($rows) {}
};
$data = $import->toCollection("imported-files/import.xlsx", 'local')->get(0);

$data is a collection now. The ->get(0) function gets the first sheet of the excel file.

The first two params for the toCollection function are path and storage disk name, if you have the file stored in a storage disk in laravel. In this example it will look in the folder /storage/app/imported-files/import.xlsx if you did not modify the local storage disk config.

You can also enter the absolute path of the file like so:

$data = $import->toCollection('/var/www/html/storage/app/imported-file.xlsx')->get(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment