参考网站:http://www./laravel-excel/docs/export

Simple Excel Export

Basics

A new file can be created using the create method with the filename as first parameter.

Excel::create('Filename');

To manipulate the creation of the file you can use the callback

Excel::create('Filename', function($excel) {

    // Call writer methods here

});

Changing properties

There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See app/config/packages/maatwebsite/excel/config.php.

Excel::create('Filename', function($excel) {

    // Set the title
    $excel->setTitle('Our new awesome title');

    // Chain the setters
    $excel->setCreator('Maatwebsite')
          ->setCompany('Maatwebsite');

    // Call them separately
    $excel->setDescription('A demonstration to change the file properties');

});

Go to the reference guide to see a list of available properties.

Exporting

To download the created file, use ->export($ext) or ->download($ext).

Export to Excel5 (xls)

Excel::create('Filename', function($excel) {

})->export('xls');

// or
->download('xls');

Export to Excel2007 (xlsx)

->export('xlsx');

// or
->download('xlsx');

Export to CSV

->export('csv');

// or
->download('csv');

You can set the default enclosure and delimiter inside the config

Export to PDF

To export files to pdf, you will have to include "dompdf/dompdf": "~0.6.1""mpdf/mpdf": "~5.7.3" or"tecnick.com/tcpdf": "~6.0.0" in your composer.json and change the export.pdf.driver config setting accordingly.

->export('pdf');

NewExcelFile injections

Following the Laravel 5.0 philosophy with its new awesome FormRequest injections, we introduce you NewExcelFile injections.

NewExcelFile class

This NewExcelFile is a wrapper for a new Excel file. Inside the getFilename() you can declare the wanted filename.

class UserListExport extends \Maatwebsite\Excel\Files\NewExcelFile {

    public function getFilename()
    {
        return 'filename';
    }
}

Usage

You can inject these NewExcelFiles inside the __constructor or inside the method (when using Laravel 5.0), in e.g. the controller.

class ExampleController extends Controller {

    public function exportUserList(UserListExport $export)
    {
        // work on the export
        return $export->sheet('sheetName', function($sheet)
        {

        })->export('xls');
    }

}

Export Handlers

To decouple your Excel-export code completely from the controller, you can use the export handlers.

class ExampleController extends Controller {

    public function exportUserList(UserListExport $export)
    {
        // Handle the export
        $export->handleExport();
    }

}

The handleExport() method will dynamically call a handler class which is your class name appended with Handler

class UserListExportHandler implements \Maatwebsite\Excel\Files\ExportHandler {

    public function handle(UserListExport $export)
    {
        // work on the export
        return $export->sheet('sheetName', function($sheet)
        {

        })->export('xls');
    }

}

Store on server

To store the created file on the server, use ->store($ext, $path = false, $returnInfo = false) or ->save().

Normal export to default storage path

By default the file will be stored inside the app/storage/exports folder, which has been defined in the export.phpconfig file.

Excel::create('Filename', function($excel) {

    // Set sheets

})->store('xls');

Normal export to custom storage path

If you want to use a custom storage path (e.g. to separate the files per client), you can set the folder as the second parameter.

->store('xls', storage_path('excel/exports'));

Store and export

->store('xls')->export('xls');

Store and return storage info

If you want to return storage information, set the third paramter to true or change the config setting insideexport.php.

->store('xls', false, true);
KeyExplanation
fullFull path with filename
pathPath without filename
fileFilename
titleFile title
extFile extension

Make sure your storage folder is writable!

Sheets

Creating a sheet

To create a new sheet inside our newly created file, use ->sheet('Sheetname').

Excel::create('Filename', function($excel) {

    $excel->sheet('Sheetname', function($sheet) {

        // Sheet manipulation

    });

})->export('xls');

Creating multiple sheets

You can set as many sheets as you like inside the file:

Excel::create('Filename', function($excel) {

    // Our first sheet
    $excel->sheet('First sheet', function($sheet) {

    });

    // Our second sheet
    $excel->sheet('Second sheet', function($sheet) {

    });

})->export('xls');

Changing properties

There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See app/config/packages/maatwebsite/excel/config.php.

Excel::create('Filename', function($excel) {

    $excel->sheet('Sheetname', function($sheet) {

        $sheet->setOrientation('landscape');

    });

})->export('xls');

Go to the reference guide to see a list of available properties.

Default page margin

It's possible to set the default page margin inside the config file excel::export.sheets. It accepts boolean, single value or array.

To manually set the page margin you can use: ->setPageMargin()

// Set top, right, bottom, left
$sheet->setPageMargin(array(
    0.25, 0.30, 0.25, 0.30
));

// Set all margins
$sheet->setPageMargin(0.25);

Password protecting a sheet

A sheet can be password protected with $sheet->protect():

// Default protect
$sheet->protect('password');

// Advanced protect
$sheet->protect('password', function(\PHPExcel_Worksheet_Protection $protection) {
    $protection->setSort(true);
});

Creating a sheet from an array

Array

To create a new file from an array use->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration) inside the sheet closure.

Excel::create('Filename', function($excel) {

    $excel->sheet('Sheetname', function($sheet) {

        $sheet->fromArray(array(
            array('data1', 'data2'),
            array('data3', 'data4')
        ));

    });

})->export('xls');

Alternatively you can use ->with().

$sheet->with(array(
    array('data1', 'data2'),
    array('data3', 'data4')
));

If you want to pass variables inside the closure, use use($data)

$data = array(
    array('data1', 'data2'),
    array('data3', 'data4')
);

Excel::create('Filename', function($excel) use($data) {

    $excel->sheet('Sheetname', function($sheet) use($data) {

        $sheet->fromArray($data);

    });

})->export('xls');

Null comparision

By default 0 is shown as an empty cell. If you want to change this behaviour, you can pass true as 4th parameter:

// Will show 0 as 0
$sheet->fromArray($data, null, 'A1', true);

To change the default behaviour, you can use excel::export.sheets.strictNullComparison config setting.

Eloquent model

It's also possible to pass an Eloquent model and export it by using ->fromModel($model). The method accepts the same parameters as fromArray

Auto heading generation

By default the export will use the keys of your array (or model attribute names) as first row (header column). To change this behaviour you can edit the default config setting (excel::export.generate_heading_by_indices) or passfalse as 5th parameter:

// Won't auto generate heading columns
$sheet->fromArray($data, null, 'A1', false, false);

Row manipulation

Manipulate certain row

Change cell values

// Manipulate first row
$sheet->row(1, array(
     'test1', 'test2'
));

// Manipulate 2nd row
$sheet->row(2, array(
    'test3', 'test4'
));

Manipulate row cells

// Set black background
$sheet->row(1, function($row) {

    // call cell manipulation methods
    $row->setBackground('#000000');

});

Append row

// Append row after row 2
$sheet->appendRow(2, array(
    'appended', 'appended'
));

// Append row as very last
$sheet->appendRow(array(
    'appended', 'appended'
));

Prepend row

// Add before first row
$sheet->prependRow(1, array(
    'prepended', 'prepended'
));

// Add as very first
$sheet->prependRow(array(
    'prepended', 'prepended'
));

Append multiple rows

// Append multiple rows
$sheet->rows(array(
    array('test1', 'test2'),
    array('test3', 'test4')
));

// Append multiple rows
$sheet->rows(array(
    array('test5', 'test6'),
    array('test7', 'test8')
));

Cell manipulation

$sheet->cell('A1', function($cell) {

    // manipulate the cell

});

$sheet->cells('A1:A5', function($cells) {

    // manipulate the range of cells

});

Set background

To change the background of a range of cells we can use ->setBackground($color, $type, $colorType)

// Set black background
$cells->setBackground('#000000');

Change fonts

// Set with font color
$cells->setFontColor('#ffffff');

// Set font family
$cells->setFontFamily('Calibri');

// Set font size
$cells->setFontSize(16);

// Set font weight to bold
$cells->setFontWeight('bold');

// Set font
$cells->setFont(array(
    'family'     => 'Calibri',
    'size'       => '16',
    'bold'       =>  true
));

Set borders

// Set all borders (top, right, bottom, left)
$cells->setBorder('solid', 'none', 'none', 'solid');

// Set borders with array
$cells->setBorder(array(
    'borders' => array(
        'top'   => array(
            'style' => 'solid'
        ),
    )
));

Set horizontal alignment

// Set alignment to center
$cells->setAlignment('center');

Set vertical alignment

// Set vertical alignment to middle
 $cells->setValignment('middle');

Sheet styling

General styling

If you want to change the general styling of your sheet (not cell or range specific), you can use the ->setStyle()method.

// Set font with ->setStyle()`
$sheet->setStyle(array(
    'font' => array(
        'name'      =>  'Calibri',
        'size'      =>  15,
        'bold'      =>  true
    )
));

Fonts

To change the font for the current sheet use ->setFont($array):

$sheet->setFont(array(
    'family'     => 'Calibri',
    'size'       => '15',
    'bold'       => true
));

Separate setters

// Font family
$sheet->setFontFamily('Comic Sans MS');

// Font size
$sheet->setFontSize(15);

// Font bold
$sheet->setFontBold(true);

Borders

You can set borders for the sheet, by using:

// Sets all borders
$sheet->setAllBorders('thin');

// Set border for cells
$sheet->setBorder('A1', 'thin');

// Set border for range
$sheet->setBorder('A1:F10', 'thin');

Go to the reference guide to see a list of available border styles

Freeze rows

If you want to freeze a cell, row or column, use:

// Freeze first row
$sheet->freezeFirstRow();

// Freeze the first column
$sheet->freezeFirstColumn();

// Freeze the first row and column
$sheet->freezeFirstRowAndColumn();

// Set freeze
$sheet->setFreeze('A2');

Auto filter

To enable the auto filter use ->setAutoFilter($range = false).

// Auto filter for entire sheet
$sheet->setAutoFilter();

// Set auto filter for a range
$sheet->setAutoFilter('A1:E10');

Cell size

Set column width

To set the column width use ->setWidth($cell, $width).

// Set width for a single column
$sheet->setWidth('A', 5);

// Set width for multiple cells
$sheet->setWidth(array(
    'A'     =>  5,
    'B'     =>  10
));

Set row height

To set the row height use ->setHeight($row, $height).

// Set height for a single row
$sheet->setHeight(1, 50);

// Set height for multiple rows
$sheet->setHeight(array(
    1     =>  5