Yii 2 Export Menu

Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads
Thankful to Krajee!
to get more out of us.

NOTE: This extension depends on the kartik-v/yii2-krajee-base extension which in turn depends on the yiisoft/yii2-bootstrap extension. Check the composer.json for this extension's requirements and dependencies that may be updated by composer.

The yii2-export extension allows you to export data from your database, server, or other source in various formats (e.g. excel, html, pdf, csv etc.) using the popular PHP Excel library. The extension simplifies this by rendering an export menu (via ExportMenu widget) that generates a export link for each format and can accept input data from a yii\data\DataProvider.

The ExportMenu widget has a configuration very similar to the kartik\grid\GridView widget. It extends the kartik\grid\GridView widget and can thus be configured with a dataProvider and columns property just like any GridView. However, the difference is that widget will be used for exporting the complete data and hence WOULD NOT render the grid by default. It thus does not involve any overhead of publishing GridView related assets OR run validations for filters or sorts directly. Instead, it displays the menu / list of export actions in form of a bootstrap styled ButtonDropdown menu or a simple HTML list which one can style as needed.

This menu can be easily embedded and within the \kartik\grid\GridView toolbar and complements the client export functionality of \kartik\grid\GridView. It can alternatively be used with the default kartik\grid\GridView as well, OR it can also be implemented as a separate component in isolation in your view.

View a complete demo.

The preferred way to install this extension is through composer. Either run:

$ php composer.phar require kartik-v/yii2-export "*"

or add:

"kartik-v/yii2-export": "*"

to the require section of your composer.json file. Then run:

php composer.phar update

to get the updated package on your application install.

The Export Menu extends the \kartik\grid\GridView widget, and thus allows you to setup your export menu just like a GridView using most of the GridView properties.


The following GridView properties are mandatory and important:


dataProvider

yii\data\DataProviderInterface, is the data provider for the Export Menu. See yii\grid\GridView::dataProvider for more details.

columns

array, is the Grid column data configuration to be displayed in the Exported data output. See yii\grid\GridView::columns for more details.

emptyText

string, the HTML content to be displayed when dataProvider does not have any data OR if no columns are selected for export. See yii\grid\GridView::emptyText for more details.


In addition to the above, the following additional properties are specially recognized for ExportMenu:


target

string, the target for submitting the export form, which will trigger the download of the exported file. Defaults to ExportMenu::TARGET_POPUP. Must be one of the following:

  • ExportMenu::TARGET_POPUP or _popup: whereby a popup window with download progress message is displayed.

  • ExportMenu::TARGET_BLANK or _blank: whereby a new blank window is displayed and closed after download is finished.

  • ExportMenu::TARGET_SELF or _self: no window is popped up in this case, but download is submitted on same page.

NOTE: Note if you set stream to false, then this will be overridden to ExportMenu::TARGET_SELF.

krajeeDialogSettings

array, configuration settings for the Krajee dialog widget (yii2-dialog) that will be used to render alerts and confirmation dialog prompts. Note that the yii2-dialog extension must be installed and available.

showConfirmAlert

boolean, whether to show a confirmation alert dialog before download. This confirmation dialog will notify user about the type of exported file for download and to disable popup blockers. Defaults to true.

enableFormatter

boolean, whether to enable the yii gridview formatter component for formatting columns. Defaults to true. If set to false, this will render content as raw format.

asDropdown

string, the HTML content to be displayed when dataProvider does not have any data OR if no columns are selected for export.

dropdownOptions

array, is the HTML attributes for the export button menu. Applicable only if asDropdown is set to true. Defaults to ['class' => 'btn btn-default']. The following special options are available:

  • icon: string, label for the dropdown defaults to <i class="glyphicon glyphicon-export"></i>

  • label: string, label for the dropdown defaults to empty string.

  • title: string, title to display on hover of the export menu dropdown button. Defaults to Export data in selected format.

  • itemsBefore: array, any additional items that will be merged/prepended before with the export dropdown list. This should be similar to the items property as supported by \yii\bootstrap\ButtonDropdown widget.

  • itemsAfter: array, any additional items that will be merged/appended after with the export dropdown list. This should be similar to the items property as supported by \yii\bootstrap\ButtonDropdown widget.

  • menuOptions: array, is the HTML attributes for the dropdown menu.

pjaxContainerId

string, the pjax container identifier inside which this menu is being rendered. If set the jQuery export menu plugin will get auto initialized on pjax request completion.

clearBuffers

boolean, whether to clear all previous / parent output buffers. Defaults to false.

initProvider

boolean, whether to initialize data provider and clear models before rendering. Defaults to false.

showColumnSelector

boolean, whether to show a column selector to select columns for export. Defaults to true. Note that in addition to this the asDropdown must be set to true, for the column selector to be displayed.

columnSelector

array, the configuration of the column names in the column selector. Note: column names will be auto-generated anyway. Any setting in this property will override the auto-generated column names. This list should be setup as $key => $value where:

  • key: int, is the zero based index for the column as set in columns.

  • value: string, is the column name/label you wish to display in the column selector.

columnSelectorOptions

array, is the HTML attributes for the column selector dropdown button. Applicable only if asDropdown and showColumnSelector is set to true. Defaults to ['class' => 'btn btn-default']. The following special options are available:

  • icon: string, label for the dropdown defaults to <i class="glyphicon glyphicon-list"></i>

  • label: string, label for the dropdown defaults to empty string.

  • title: string, title to display on hover of the export menu dropdown button. Defaults to Select columns for export.

columnSelectorMenuOptions

array, is the HTML attributes for the column selector menu list (UL tag). Applicable only if asDropdown and showColumnSelector is set to true.

columnBatchToggleSettings

array,the settings for the toggle all checkbox to check/uncheck the columns as a batch. Should be setup as an associative array which can have the following keys:

  • show: boolean, whether the batch toggle checkbox is to be shown. Defaults to true.

  • label: string, the label to be displayed for toggle all checkbox. Defaults to Toggle All.

  • options: array, the HTML attributes for the toggle label text. Defaults to ['class'=>'kv-toggle-all'].

container

array, HTML attributes for the container to wrap the widget. Defaults to ['class'=>'btn-group', 'role'=>'group']].

template

string, the template for rendering the content in the container. This will be parsed only if asDropdown is true. Defaults to {columns}\n{menu}. The following tags will automatically be parsed and replaced:

  • {columns}: will be replaced with columns selector dropdown

  • {menu}: will be replaced with export menu dropdown

timeout

integer, timeout for the export function (in seconds), if timeout is < 0, the default PHP timeout will be used.

exportFormOptions

array, HTML attributes for the export form generated..

selectedColumns

array, the list of column indexes that will be pre-selected in the column selector. If this is not set, all columns in column selector will be pre-selected.

disabledColumns

array, the list of column indexes that will be disabled in the column selector. The disabled column will be pre-selected and displayed for export based on selectedColumns setting.

hiddenColumns

array, the list of column indexes that will be hidden in the column selector. The hidden column will be pre-selected and displayed for export based on selectedColumns setting.

noExportColumns

array, the list of column indexes that will be hidden in the column selector as well as the export (this will not validate any column setting from selectedColumns).

exportFormView

string, the view file for rendering the export form. Defaults to _form in the widget views directory.

exportColumnsView

string, the view file for rendering the export columns selector. Defaults to _columns in the widget views directory.

exportConfig

array, is the configuration for each export format above. This must be setup as an associative array as $key => $setting pairs. The array keys ($key) must be the one of the format constants:

  • ExportMenu::FORMAT_HTML or 'HTML'

  • ExportMenu::FORMAT_CSV or 'CSV'

  • ExportMenu::FORMAT_TEXT or 'TXT'

  • ExportMenu::FORMAT_PDF or 'PDF'

  • ExportMenu::FORMAT_EXCEL or 'Excel5'

  • ExportMenu::FORMAT_EXCEL_X or 'Excel2007'

The array values ($setting) for each of the keys above can be a boolean false value OR a configuration array containing the following options:

  • icon string, is the glyphicon or font-awesome name suffix to be displayed before the export menu item label. The font awesome icons will be used, if you have setup fontAwesome propery to true. to be displayed before the export menu item label. If set to an empty string, this will not be displayed. For glyphicons, it defaults to one of the 'floppy-' glyphicons available in bootstrap.

    Note:

    You must load the font awesome CSS file in your view or layout, if fontAwesome is set to true, so that icons would be properly rendered.
  • iconOptions: array, HTML attributes for export menu icon.

  • linkOptions: array, HTML attributes for each export item link.

  • label string, is the label for the export format menu item displayed.

  • extension string, is the extension for the above file name.

  • alertMsg string, is the message prompt to show before saving. If this is empty or not set it will not be displayed.

  • mime string, is the mime type (for the file format) to be set before downloading.

  • writer string, is the PHP Excel writer type.

  • options: array, HTML attributes for export menu item.

Note

To disable a format that you do not need, you can set the format $settings as false or an empty array. For example to disable TEXT and PDF:
exportConfig => [
    ExportMenu::FORMAT_TEXT => false,
    ExportMenu::FORMAT_PDF => false
]

The exportConfig if not set will default to the following:

[
    ExportMenu::FORMAT_HTML => [
        'label' => Yii::t('kvexport', 'HTML'),
        'icon' => $isFa ? 'file-text' : 'floppy-saved',
        'iconOptions' => ['class' => 'text-info'],
        'linkOptions' => [],
        'options' => ['title' => Yii::t('kvexport', 'Hyper Text Markup Language')],
        'alertMsg' => Yii::t('kvexport', 'The HTML export file will be generated for download.'),
        'mime' => 'text/html',
        'extension' => 'html',
        'writer' => 'HTML'
    ],
    ExportMenu::FORMAT_CSV => [
        'label' => Yii::t('kvexport', 'CSV'),
        'icon' => $isFa ? 'file-code-o' : 'floppy-open',
        'iconOptions' => ['class' => 'text-primary'],
        'linkOptions' => [],
        'options' => ['title' => Yii::t('kvexport', 'Comma Separated Values')],
        'alertMsg' => Yii::t('kvexport', 'The CSV export file will be generated for download.'),
        'mime' => 'application/csv',
        'extension' => 'csv',
        'writer' => 'CSV'
    ],
    ExportMenu::FORMAT_TEXT => [
        'label' => Yii::t('kvexport', 'Text'),
        'icon' => $isFa ? 'file-text-o' : 'floppy-save',
        'iconOptions' => ['class' => 'text-muted'],
        'linkOptions' => [],
        'options' => ['title' => Yii::t('kvexport', 'Tab Delimited Text')],
        'alertMsg' => Yii::t('kvexport', 'The TEXT export file will be generated for download.'),
        'mime' => 'text/plain',
        'extension' => 'csv',
        'writer' => 'CSV'
    ],
    ExportMenu::FORMAT_PDF => [
        'label' => Yii::t('kvexport', 'PDF'),
        'icon' => $isFa ? 'file-pdf-o' : 'floppy-disk',
        'iconOptions' => ['class' => 'text-danger'],
        'linkOptions' => [],
        'options' => ['title' => Yii::t('kvexport', 'Portable Document Format')],
        'alertMsg' => Yii::t('kvexport', 'The PDF export file will be generated for download.'),
        'mime' => 'application/pdf',
        'extension' => 'pdf',
        'writer' => 'PDF'
    ],
    ExportMenu::FORMAT_EXCEL => [
        'label' => Yii::t('kvexport', 'Excel 95 +'),
        'icon' => $isFa ? 'file-excel-o' : 'floppy-remove',
        'iconOptions' => ['class' => 'text-success'],
        'linkOptions' => [],
        'options' => ['title' => Yii::t('kvexport', 'Microsoft Excel 95+ (xls)')],
        'alertMsg' => Yii::t('kvexport', 'The EXCEL 95+ (xls) export file will be generated for download.'),
        'mime' => 'application/vnd.ms-excel',
        'extension' => 'xls',
        'writer' => 'Excel5'
    ],
    ExportMenu::FORMAT_EXCEL_X => [
        'label' => Yii::t('kvexport', 'Excel 2007+'),
        'icon' => $isFa ? 'file-excel-o' : 'floppy-remove',
        'iconOptions' => ['class' => 'text-success'],
        'linkOptions' => [],
        'options' => ['title' => Yii::t('kvexport', 'Microsoft Excel 2007+ (xlsx)')],
        'alertMsg' => Yii::t('kvexport', 'The EXCEL 2007+ (xlsx) export file will be generated for download.'),
        'mime' => 'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'extension' => 'xlsx',
        'writer' => 'Excel2007'
    ],
]

exportRequestParam

string, is the request parameter (received via $_GET or $_POST response) that will be submitted during export. This should be unique for each export menu widget (for multiple export menu widgets on same page). If not set this will be auto generated.

fontAwesome

boolean, whether to use font awesome icons for rendering the icons as defined in exportConfig. If set to true, you must load the FontAwesome CSS separately in your application.

styleOptions

array, is the output style configuration options setup as an associative array: $key => $setting. The $key must be one of ExportMenu::FORMAT_EXCEL and/or ExportMenu::FORMAT_EXCEL_X. The $setting must be the style configuration array as required by PHPExcel. The following configuration is defaulted for styleOptions:

[
    ExportMenu::FORMAT_EXCEL => [
        'font' => [
            'bold' => true,
            'color' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
        'fill' => [
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => [
                'argb' => '00000000',
            ],
        ],
    ],
    ExportMenu::FORMAT_EXCEL_X => [
        'font' => [
            'bold' => true,
            'color' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
        'fill' => [
            'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
            'startcolor' => [
                'argb' => 'FFA0A0A0',
            ],
            'endcolor' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
    ],
]

contentBefore

array, an array of rows to prepend in front of the exported grid. This can be used to add content like a table caption/title. The array can be configured with the following keys:

  • value: string, the value of the merged row

  • styleOptions: array, array of configuration options to set the style. See styleOptions on the various settings to configure.

contentAfter

array, an array of rows to append in end of the exported grid. This can be used to extend content in table footer. The array can be configured with the following keys:

  • value: string, the value of the merged row

  • styleOptions: array, array of configuration options to set the style. See styleOptions on the various settings to configure.

autoWidth

boolean, whether to auto-size the excel output column widths. Defaults to true.

encoding

string, is the encoding the downloaded file header. Defaults to 'utf8'.

filename

string, is the exported output file name. Defaults to 'grid-export'.

stream

boolean, whether to stream output directly to the browser. Defaults to true.

deleteAfterSave

boolean, whether to delete file after saving file to the set folder.

afterSaveView

string|boolean, the view file to show details of exported file link. This property will be validated only when stream is false. You can set this to false to not display any file link details for view. Else it defaults to _view, which will use the extension inbuilt view.

linkPath

string, the web accessible path for the saved file location. This property will be parsed only if stream is false. Note the afterSaveViewproperty that will render the displayed file link. Check the configure files link demo for details on setting this.

linkFileName

string, the name of the file to be appended to linkPath to generate the complete link. If not set, this will default to the filename. Check the configure files link demo for details on setting this.

batchSize

integer, fetch models from the dataprovider using batches (pages) of this size. Set this to 0 (the default) to disable. If $dataProvider does not have a pagination object, this parameter is ignored. Setting this property helps reduce memory overflow issues by allowing parsing of models in batches, rather than fetching all models in one go.

messages

array, is the configuration of various messages that will be displayed at runtime:

  • allowPopups: string, is the message to be shown to disable browser popups for download. Defaults to Disable any popup blockers in your browser to ensure proper download..

  • confirmDownload: string, is the message to be shown for confirming to proceed with the download. Defaults to Ok to proceed?.

  • downloadProgress: string, is the message to be shown in a popup dialog when download request is executed. Defaults to Generating file. Please wait....

  • downloadProgress: string, is the message to be shown in a popup dialog when download request is completed. Defaults to All done! Click anywhere here to close this window, once you have downloaded the file..

onInitWriter

Closure, is the callback function that is executed on initializing the writer. The anonymous function should have the following signature:

function ($writer, $grid)

where:

  • writer: PHPExcel_Writer_IWriter, is the PHPExcel writer object instance

  • grid: GridView, is the current grid object instance

onInitSheet

Closure, is the callback function that is executed on initializing the work sheet. The anonymous function should have the following signature:

function ($sheet, $grid)

where:

  • sheet: PHPExcel_Worksheet, is the PHPExcel work sheet object instance

  • grid: GridView, is the current grid object instance

onRenderHeaderCell

Closure, is the callback function that is executed on rendering the header cell output content. The anonymous function should have the following signature:

function ($cell, $content, $grid)

where:

  • cell: PHPExcel_Cell, is the PHPExcel work sheet object instance

  • content: string, is the header cell content being rendered

  • grid: GridView, is the current grid object instance

Refer the On Render Methods section for more details on the usage of these event based callbacks.

onRenderDataCell

Closure, is the callback function that is executed on rendering each body data cell output content. The anonymous function should have the following signature:

function ($cell, $content, $model, $key, $index, $grid)

where:

  • cell: PHPExcel_Cell, is the PHPExcel work sheet object instance

  • content: string, is the header cell content being rendered

  • model mixed, is the data model

  • key mixed, is the key associated with the data model

  • index integer, is the zero-based index of the data model among the models array returned by GridView::dataProvider

  • $grid: GridView, is the current grid object instance

Refer the On Render Methods section for more details on the usage of these event based callbacks.

onRenderFooterCell

Closure, is the callback function that is executed on rendering the footer cell output content. The anonymous function should have the following signature:

function ($cell, $content, $grid)

where:

  • cell: PHPExcel_Cell, is the PHPExcel work sheet object instance

  • content: string, is the footer cell content being rendered

  • grid: GridView, is the current grid object instance

Refer the On Render Methods section for more details on the usage of these event based callbacks.

onRenderSheet

Closure, is the callback function that is executed on rendering the work sheet. The anonymous function should have the following signature:

function ($sheet, $grid)

where:

  • sheet: PHPExcel_Worksheet, is the PHPExcel work sheet object instance

  • grid: GridView, is the current grid object instance

Refer the On Render Methods section for more details on the usage of these event based callbacks.

onGenerateFile

Closure, is the callback function that is executed after file is generated. The anonymous function should have the following signature:

function ($extension, $grid)

where:

  • extension: string, is the currently exported file extension

  • grid: GridView, is the current grid object instance

Refer the On Render Methods section for more details on the usage of these event based callbacks. Check the configure files link demo for details on setting this.

docProperties

array, is the PHPExcel document properties

i18n

array, is the internalization configuration for this module. Defaults to:

[
    'class' => 'yii\i18n\PhpMessageSource',
    'basePath' => '@kvexport/messages',
    'forceTranslation' => true
];

dynagrid

boolean, enable dynagrid widget functionality (yii2-dynagrid) for column selection. If set to true the inbuilt export menu column selector functionality will be disabled and not rendered and columns set as part of kartik\dynagrid\Dynagrid widget as per settings in dynagridOptions will be used. Defaults to false.

dynagridOptions

array, configuration options for the yii2-dynagrid widget (applicable when dynagrid is set to true). Defaults to:

[
    'options' => ['id' => 'dynagrid-export-menu']
]

groupedRowStyle

array, the PHP Excel style configuration for a grouped grid row. Defaults to:

[
    'font' => [
        'bold' => false,
        'color' => [
            'argb' => '000000',
        ],
    ],
    'fill' => [
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'color' => [
            'argb' => 'C9C9C9',
        ],
    ],
]

The widget offers an event based approach to manipulate PHP Excel output. This is made possible via the onRender callbacks available as properties to this widget. The following properties can be setup as an anonymous Closure callbacks, as mentioned in the widget settings section

Each of the methods above allows accesses to the current export menu grid object instance. This is available as a parameter $grid within each of the callbacks above. The following list of getters, setters, and methods could be accessible via the $grid object instance. Note that this list below is not comprehensive. All public properties and methods of ExportMenu should be accessible via the $grid object instance.

// getters
$grid->getPHPExcel(); // returns PHP Excel object instance
$grid->getPHPExcelWriter();  // returns PHP Excel Writer object instance
$grid->getPHPExcelSheet();  // returns PHP Excel Sheet object instance
$grid->getExportType(); // returns the currently selected export type

// setters
$grid->setPHPExcel($obj); // sets/overwrites the PHP Excel object
$grid->setPHPExcelWriter($obj); // sets/overwrites the PHP Excel Writer object
$grid->setPHPExcelSheet($obj); // sets/overwrites the PHP Excel Sheet object

// other methods - check the ExportMenu source for public methods and properties
$grid->destroyPHPExcel(); // destroys the current PHP excel object

An example of configuring the onRenderSheet method could be:

'onRenderSheet' => function($sheet, $grid) {
    $exportType = $grid->getExportType(); // currently selected export type
    if ($exportType == ExportMenu::FORMAT_EXCEL_X) {
        $sheet->setCellValue("A5", "=SUM(A1:A4)"); // setting a formula in cell A5
    }
}

yii2-export is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.