Export to excel yii2

Yii2 Excel Export

Latest Stable Version
Total Downloads
Latest Unstable Version
License

Note: The minimum requirement since 2.6.0 is Yii 2.0.13. The latest
version for older Yii releases is 2.5.0.

Features

  • Export data from ActiveQuery results
  • Export any other data (Array, Iterable, …)
  • Create excel files with multiple sheets
  • Format cells and values

To write the Excel file, we use the excellent PHPSpreadsheet package.

Installation

Install the package with composer:

composer require codemix/yii2-excelexport

Quickstart example

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
        ]
    ]
]);
$file->send('user.xlsx');

Find more examples below.

Configuration and Use

ExcelFile

Property Description
writerClass The file format as supported by PHPOffice. The default is PhpOfficePhpSpreadsheetWriterXlsx
sheets An array of sheet configurations (see below). The keys are used as sheet names.
fileOptions Options to pass to the constructor of mikehaertltmpFile. Available keys are prefix, suffix and directory.
Methods Description
saveAs($name) Saves the excel file under $name
send($name=null, $inline=false, $contentType = 'application/vnd.ms-excel') Sends the excel file to the browser. If $name is empty, the file is streamed for inline display, otherwhise a download dialog will open, unless $inline is true which will force inline display even if a filename is supplied.
createSheets() Only creates the sheets of the excel workbook but does not save the file. This is usually called implicitely on saveAs() and send() but can also be called manually to modify the sheets before saving.
getWriter() Returns the PhpOfficePhpSpreadsheetWriterBaseWrite instance
getWorkbook() Returns the PhpOfficePhpSpreadsheetSpreadsheet workbook instance
getTmpFile() Returns the mikehaertltmpFile instance of the temporary file

ExcelSheet

Property Description
data An array of data rows that should be used as sheet content
titles (optional) An array of column titles
types (optional) An array of types for specific columns as supported by PHPOffice, e.g. DataType::TYPE_STRING, indexed either by column name (e.g. H) or 0-based column index.
formats (optional) An array of format strings for specific columns as supported by Excel, e.g. #,##0.00, indexed either by column name (e.g. H) or 0-based column index.
formatters (optional) An array of value formatters for specific columns. Each must be a valid PHP callable whith the signature function formatter($value, $row, $data) where $value is the cell value to format, $row is the 0-based row index and $data is the current row data from the data configuration. The callbacks must be indexed either by column name (e.g. H) or by the 0-based column index.
styles (optional) An array of style configuration indexed by cell coordinates or a range.
callbacks (optional) An array of callbacks indexed by column that should be called after rendering a cell, e.g. to apply further complex styling. Each must be a valid PHP callable with the signature function callback($cell, $col, $row) where $cell is the current PhpOfficePhpSpreadsheetCellCell object and $col and $row are the 0-based column and row indices respectively.
startColumn (optional) The start column name or its 0-based index. When this is set, the 0-based offset is added to all numeric keys used anywhere in this class. Columns referenced by name will stay unchanged. Default is ‘A’.
startRow (optional) The start row. Default is 1.
Event Description
beforeRender Triggered before the sheet is rendered. The sheet is available via $event->sender->getSheet().
afterRender Triggered after the sheet was rendered. The sheet is available via $event->sender->getSheet().

ActiveExcelSheet

The class extends from ExcelSheet but differs in the following properties:

Property Description
query The ActiveQuery for the row data (the data property will be ignored).
data The read-only property that returns the batched query result.
attributes (optional) The attributes to use as columns. Related attributes can be specifed in dot notation as usual, e.g. team.name. If not set, the attributes() from the corresponding ActiveRecord class will be used.
titles (optional) The column titles, indexed by column name (e.g. H) or 0-based column index. If a column is not listed here, the respective attribute label will be used. If set to false no title row will be rendered.
formats (optional) As in ExcelSheet but for date, datetime and decimal DB columns, the respective formats will be automatically set by default, according to the respective date format properties (see below) and the decimal precision.
formatters (optional) As in ExcelSheet but for date and datetime columns the value will be autoconverted to the correct excel time format with PHPExcel_Shared_Date::PHPToExcel() by default.
dateFormat The excel format to use for date DB types. Default is dd/mm/yyyy.
dateTimeFormat The excel format to use for datetime DB types. Default is dd/mm/yyyy hh:mm:ss.
batchSize The query batchsize to use. Default is 100.
modelInstance (optional) The query’s modelClass instance used to obtain attribute types and titles. If not set an instance of the query’s modelClass is created automatically.

Note Since version 2.3.1 datetime attributes will automatically be
converted to the correct timezone. This feature makes use of the current
defaultTimeZone
and
timeZone
setting of the app.

Examples

ActiveQuery results

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',

    'writerClass' => 'PhpOfficePhpSpreadsheetWriterXls', // Override default of `PhpOfficePhpSpreadsheetWriterXlsx`

    'sheets' => [

        'Active Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find()->where(['active' => true]),

            // If not specified, all attributes from `User::attributes()` are used
            'attributes' => [
                'id',
                'name',
                'email',
                'team.name',    // Related attribute
                'created_at',
            ],

            // If not specified, the label from the respective record is used.
            // You can also override single titles, like here for the above `team.name`
            'titles' => [
                'D' => 'Team Name',
            ],
        ],

    ],
]);
$file->send('demo.xlsx');

Raw data

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [

        'Result per Country' => [   // Name of the excel sheet
            'data' => [
                ['fr', 'France', 1.234, '2014-02-03 12:13:14'],
                ['de', 'Germany', 2.345, '2014-02-05 19:18:39'],
                ['uk', 'United Kingdom', 3.456, '2014-03-03 16:09:04'],
            ],

            // Set to `false` to suppress the title row
            'titles' => [
                'Code',
                'Name',
                'Volume',
                'Created At',
            ],

            'formats' => [
                // Either column name or 0-based column index can be used
                'C' => '#,##0.00',
                3 => 'dd/mm/yyyy hh:mm:ss',
            ],

            'formatters' => [
                // Dates and datetimes must be converted to Excel format
                3 => function ($value, $row, $data) {
                    return PhpOfficePhpSpreadsheetSharedDate::PHPToExcel(strtotime($value));
                },
            ],
        ],

        'Countries' => [
            // Data for another sheet goes here ...
        ],
    ]
]);
// Save on disk
$file->saveAs('/tmp/export.xlsx');

Query builder results

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [

        'Users' => [
            'data' => new (yiidbQuery)
                ->select(['id','name','email'])
                ->from('user')
                ->each(100);
            'titles' => ['ID', 'Name', 'Email'],
        ],
    ]
]);
$file->send('demo.xlsx');

Styling

Since version 2.3.0 you can style single cells and cell ranges via the styles
property of a sheet. For details on the accepted styling format please consult the
PhpSpreadsheet documentation.

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'styles' => [
                'A1:Z1000' => [
                    'font' => [
                        'bold' => true,
                        'color' => ['rgb' => 'FF0000'],
                        'size' => 15,
                        'name' => 'Verdana'
                    ],
                    'alignment' => [
                        'horizontal' => Alignment::HORIZONTAL_RIGHT,
                    ],
                ],
            ],
        ]
    ]
]);

As you have access to the PHPExcel object you can also «manually» modify the excel file as you like.

<?php
// Create the actual workbook and sheets
$file->createSheets();
$file
    ->getWorkbook();
    ->getSheet(1)
    ->getStyle('B1')
    ->getFont()
    ->getColor()
    ->setARGB(PhpOfficePhpSpreadsheetStyleColor::COLOR_RED);
$file->send();

Alternatively you can also use the callback feature from our ExcelSheet:

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'callbacks' => [
                // $cell is a PhpOfficePhpSpreadsheetCell object
                'A' => function ($cell, $row, $column) {
                    $cell->getStyle()->applyFromArray([
                        'font' => [
                            'bold' => true,
                        ],
                        'alignment' => [
                            'horizontal' => PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_RIGHT,
                        ],
                        'borders' => [
                            'top' => [
                                'style' => PhpOfficePhpSpreadsheetStyleBorder::BORDER_THIN,
                            ],
                        ],
                        'fill' => [
                            'fillType' => PhpOfficePhpSpreadsheetStyleFill::FILL_GRADIENT_LINEAR,
                            'rotation' => 90,
                            'startColor' => [
                                'argb' => 'FFA0A0A0',
                            ],
                            'endColor' => [
                                'argb' => 'FFFFFFFF',
                            ],
                        ],
                    ]);
                },
            ],
        ],
    ],
]);

Events

Since version 2.5.0 there are new events which make it easier to further modify each sheet.

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'startRow' => 3,
            'on beforeRender' => function ($event) {
                $sheet = $event->sender->getSheet();
                $sheet->setCellValue('A1', 'List of current users');
            }
        ],
    ],
]);
  1. Features
  2. Example
  3. Documentation

This is yet another extension to export data to excel with main focus on simplicity.

Features

  • Export data from ActiveQuery results
  • Export any other data (Array, Iterable, …)
  • Create excel files with multiple sheets
  • Format cells and values

Example

$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
        ]
    ]
]);
$file->send('user.xlsx');

Documentation

Find the full docs on our project site on Github:

https://github.com/codemix/yii2-excelexport

A utility to quickly create Excel files from query results or raw data

  • dev-master

  • 2.8.2

  • 2.8.1

  • 2.8.0

  • 2.7.2

  • 2.7.1

  • 2.7.0

  • 2.6.0

  • 2.5.0

  • 2.4.0

  • 2.3.1

  • 2.3.0

  • 2.2.0

  • 2.1.0

  • 2.0.0

  • 1.0.1

  • 1.0.0

  • 1.0.0-alpha

This package is auto-updated.

Last update: 2023-03-18 15:50:37 UTC


README

Latest Stable Version
Total Downloads
Latest Unstable Version
License

Note: The minimum requirement since 2.6.0 is Yii 2.0.13. The latest
version for older Yii releases is 2.5.0.

Features

  • Export data from ActiveQuery results
  • Export any other data (Array, Iterable, …)
  • Create excel files with multiple sheets
  • Format cells and values

To write the Excel file, we use the excellent PHPSpreadsheet package.

Installation

Install the package with composer:

composer require codemix/yii2-excelexport

Quickstart example

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
        ]
    ]
]);
$file->send('user.xlsx');

Find more examples below.

Configuration and Use

ExcelFile

Property Description
writerClass The file format as supported by PHPOffice. The default is PhpOfficePhpSpreadsheetWriterXlsx
sheets An array of sheet configurations (see below). The keys are used as sheet names.
fileOptions Options to pass to the constructor of mikehaertltmpFile. Available keys are prefix, suffix and directory.
Methods Description
saveAs($name) Saves the excel file under $name
send($name=null, $inline=false, $contentType = 'application/vnd.ms-excel') Sends the excel file to the browser. If $name is empty, the file is streamed for inline display, otherwhise a download dialog will open, unless $inline is true which will force inline display even if a filename is supplied.
createSheets() Only creates the sheets of the excel workbook but does not save the file. This is usually called implicitely on saveAs() and send() but can also be called manually to modify the sheets before saving.
getWriter() Returns the PhpOfficePhpSpreadsheetWriterBaseWrite instance
getWorkbook() Returns the PhpOfficePhpSpreadsheetSpreadsheet workbook instance
getTmpFile() Returns the mikehaertltmpFile instance of the temporary file

ExcelSheet

Property Description
data An array of data rows that should be used as sheet content
titles (optional) An array of column titles
types (optional) An array of types for specific columns as supported by PHPOffice, e.g. DataType::TYPE_STRING, indexed either by column name (e.g. H) or 0-based column index.
formats (optional) An array of format strings for specific columns as supported by Excel, e.g. #,##0.00, indexed either by column name (e.g. H) or 0-based column index.
formatters (optional) An array of value formatters for specific columns. Each must be a valid PHP callable whith the signature function formatter($value, $row, $data) where $value is the cell value to format, $row is the 0-based row index and $data is the current row data from the data configuration. The callbacks must be indexed either by column name (e.g. H) or by the 0-based column index.
styles (optional) An array of style configuration indexed by cell coordinates or a range.
callbacks (optional) An array of callbacks indexed by column that should be called after rendering a cell, e.g. to apply further complex styling. Each must be a valid PHP callable with the signature function callback($cell, $col, $row) where $cell is the current PhpOfficePhpSpreadsheetCellCell object and $col and $row are the 0-based column and row indices respectively.
startColumn (optional) The start column name or its 0-based index. When this is set, the 0-based offset is added to all numeric keys used anywhere in this class. Columns referenced by name will stay unchanged. Default is ‘A’.
startRow (optional) The start row. Default is 1.
Event Description
beforeRender Triggered before the sheet is rendered. The sheet is available via $event->sender->getSheet().
afterRender Triggered after the sheet was rendered. The sheet is available via $event->sender->getSheet().

ActiveExcelSheet

The class extends from ExcelSheet but differs in the following properties:

Property Description
query The ActiveQuery for the row data (the data property will be ignored).
data The read-only property that returns the batched query result.
attributes (optional) The attributes to use as columns. Related attributes can be specifed in dot notation as usual, e.g. team.name. If not set, the attributes() from the corresponding ActiveRecord class will be used.
titles (optional) The column titles, indexed by column name (e.g. H) or 0-based column index. If a column is not listed here, the respective attribute label will be used. If set to false no title row will be rendered.
formats (optional) As in ExcelSheet but for date, datetime and decimal DB columns, the respective formats will be automatically set by default, according to the respective date format properties (see below) and the decimal precision.
formatters (optional) As in ExcelSheet but for date and datetime columns the value will be autoconverted to the correct excel time format with PHPExcel_Shared_Date::PHPToExcel() by default.
dateFormat The excel format to use for date DB types. Default is dd/mm/yyyy.
dateTimeFormat The excel format to use for datetime DB types. Default is dd/mm/yyyy hh:mm:ss.
batchSize The query batchsize to use. Default is 100.
modelInstance (optional) The query’s modelClass instance used to obtain attribute types and titles. If not set an instance of the query’s modelClass is created automatically.

Note Since version 2.3.1 datetime attributes will automatically be
converted to the correct timezone. This feature makes use of the current
defaultTimeZone
and
timeZone
setting of the app.

Examples

ActiveQuery results

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',

    'writerClass' => 'PhpOfficePhpSpreadsheetWriterXls', // Override default of `PhpOfficePhpSpreadsheetWriterXlsx`

    'sheets' => [

        'Active Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find()->where(['active' => true]),

            // If not specified, all attributes from `User::attributes()` are used
            'attributes' => [
                'id',
                'name',
                'email',
                'team.name',    // Related attribute
                'created_at',
            ],

            // If not specified, the label from the respective record is used.
            // You can also override single titles, like here for the above `team.name`
            'titles' => [
                'D' => 'Team Name',
            ],
        ],

    ],
]);
$file->send('demo.xlsx');

Raw data

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [

        'Result per Country' => [   // Name of the excel sheet
            'data' => [
                ['fr', 'France', 1.234, '2014-02-03 12:13:14'],
                ['de', 'Germany', 2.345, '2014-02-05 19:18:39'],
                ['uk', 'United Kingdom', 3.456, '2014-03-03 16:09:04'],
            ],

            // Set to `false` to suppress the title row
            'titles' => [
                'Code',
                'Name',
                'Volume',
                'Created At',
            ],

            'formats' => [
                // Either column name or 0-based column index can be used
                'C' => '#,##0.00',
                3 => 'dd/mm/yyyy hh:mm:ss',
            ],

            'formatters' => [
                // Dates and datetimes must be converted to Excel format
                3 => function ($value, $row, $data) {
                    return PhpOfficePhpSpreadsheetSharedDate::PHPToExcel(strtotime($value));
                },
            ],
        ],

        'Countries' => [
            // Data for another sheet goes here ...
        ],
    ]
]);
// Save on disk
$file->saveAs('/tmp/export.xlsx');

Query builder results

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [

        'Users' => [
            'data' => new (yiidbQuery)
                ->select(['id','name','email'])
                ->from('user')
                ->each(100);
            'titles' => ['ID', 'Name', 'Email'],
        ],
    ]
]);
$file->send('demo.xlsx');

Styling

Since version 2.3.0 you can style single cells and cell ranges via the styles
property of a sheet. For details on the accepted styling format please consult the
PhpSpreadsheet documentation.

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'styles' => [
                'A1:Z1000' => [
                    'font' => [
                        'bold' => true,
                        'color' => ['rgb' => 'FF0000'],
                        'size' => 15,
                        'name' => 'Verdana'
                    ],
                    'alignment' => [
                        'horizontal' => Alignment::HORIZONTAL_RIGHT,
                    ],
                ],
            ],
        ]
    ]
]);

As you have access to the PHPExcel object you can also «manually» modify the excel file as you like.

<?php
// Create the actual workbook and sheets
$file->createSheets();
$file
    ->getWorkbook();
    ->getSheet(1)
    ->getStyle('B1')
    ->getFont()
    ->getColor()
    ->setARGB(PhpOfficePhpSpreadsheetStyleColor::COLOR_RED);
$file->send();

Alternatively you can also use the callback feature from our ExcelSheet:

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'callbacks' => [
                // $cell is a PhpOfficePhpSpreadsheetCell object
                'A' => function ($cell, $row, $column) {
                    $cell->getStyle()->applyFromArray([
                        'font' => [
                            'bold' => true,
                        ],
                        'alignment' => [
                            'horizontal' => PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_RIGHT,
                        ],
                        'borders' => [
                            'top' => [
                                'style' => PhpOfficePhpSpreadsheetStyleBorder::BORDER_THIN,
                            ],
                        ],
                        'fill' => [
                            'fillType' => PhpOfficePhpSpreadsheetStyleFill::FILL_GRADIENT_LINEAR,
                            'rotation' => 90,
                            'startColor' => [
                                'argb' => 'FFA0A0A0',
                            ],
                            'endColor' => [
                                'argb' => 'FFFFFFFF',
                            ],
                        ],
                    ]);
                },
            ],
        ],
    ],
]);

Events

Since version 2.5.0 there are new events which make it easier to further modify each sheet.

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'startRow' => 3,
            'on beforeRender' => function ($event) {
                $sheet = $event->sender->getSheet();
                $sheet->setCellValue('A1', 'List of current users');
            }
        ],
    ],
]);

$title = 'Consumers Report';
$model = new Review();

$objPHPExcel = new PhpOfficePhpSpreadsheetSpreadsheet();
$sheet=0;

$objPHPExcel->setActiveSheetIndex($sheet);

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel->getActiveSheet()->setTitle($title);

$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, $model->getAttributeLabel('name'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 1, $model->getAttributeLabel('mobile'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 1, $model->getAttributeLabel('email'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, 1, $model->getAttributeLabel('email_verified'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, 1, $model->getAttributeLabel('status'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, 1, $model->getAttributeLabel('previously_ordered'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, 1, $model->getAttributeLabel('created_at'));

foreach ($data->getModels() as $dk => $dv){
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $dk+2, $dv->name);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $dk+2, $dv->mobile);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $dk+2, $dv->email);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $dk+2, $dv->email_verified?"Yes":"No");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, $dk+2, Consumer::$statuses[$dv->status]);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $dk+2, $dv->getPreviouslyOrdered()?"Yes":"No");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $dk+2, date(Yii::$app->params['dateFormat'].' '.Yii::$app->params['timeFormat'], $dv->created_at));
}

header('Content-Type: application/vnd.ms-excel');
$filename = $title.".xls";
header('Content-Disposition: attachment;filename='.$filename .' ');
header('Cache-Control: max-age=0');
$objWriter = PhpOfficePhpSpreadsheetIOFactory::createWriter($objPHPExcel, 'Xls');
$objWriter->save('php://output');
die();

yii2 экспорт в excel и pdfРасширение kartik-v/yii2-export реализует богатые возможности по экспорту данных в большое количество форматов, таких как excel, html, pdf, csv и другие. В основе работы расширения лежит библиотека phpexcel.

Виджет расширения позволяет настроить dataProvider, столбцы, так же просто, как yiigridGridView. В тоже время, он отображает только ButtonDropDown меню, которое можно подключить к любому GridView или другому компоненту.

Демонстрация работы и документация по расширению доступны на его странице.

Версия расширения 1.2.0 так же, поддерживает отображение селектора для выбора столбцов, которые необходимо включить в экспорт.

Понравилась статья? Поделить с друзьями:
  • Export to excel with php
  • Export to excel sas
  • Export excel into oracle
  • Export excel data to csv file
  • Export data to excel react