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

  • columns: array, is the Grid column data configuration to be displayed in the Exported data output.

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

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

  1. 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 and streamAfterSave to false, then this will be overridden to _self.
  2. 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.

  3. 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.

  4. asDropdown: boolean, whether to render the export menu as bootstrap button dropdown widget. Defaults to true. If set to false, this will generate a simple HTML list of links. This must be set to true, for the column selector to be displayed.

  5. 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.

  6. 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.

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

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

  9. 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.

  10. 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.

  11. 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.

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

  13. 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'].

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

  15. 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

  16. exportFormOptions: array, HTML attributes for the export form generated..

  17. 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.

  18. 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.

  19. 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.

  20. 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).

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

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

  23. exportConfig: array|boolean, is the configuration for each export format above. The array keys 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 for each of the above is a configuration array containing the following:

    • 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'
        ],
    ]
    
  24. 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.

  25. styleOptions: array, is the output style configuration options. It must be the style configuration array as required by PHPExcel. The following settings are defaulted:

    Default for EXCEL 95 format:

    [
        'font' => [
            'bold' => true,
            'color' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
        'fill' => [
            'type' => PHPExcel_Style_Fill::FILL_SOLID,
            'color' => [
                'argb' => '00000000',
            ],
        ],
    ]
    

    Default for EXCEL 2007 format:

    [
        'font' => [
            'bold' => true,
            'color' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
        'fill' => [
            'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
            'startcolor' => [
                'argb' => 'FFA0A0A0',
            ],
            'endcolor' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
    ]
    
  26. 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.

  27. 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.

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

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

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

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

  32. streamAfterSave: boolean, whether to stream after saving file to folder and when stream is false. This property will be validated only when stream is false. Defaults to false.

  33. deleteAfterSave: boolean, whether to delete file after saving file to folder and when stream is false. This property will be validated only when stream is false. Defaults to false. This property is useful only if streamAfterSave is true.

  34. afterSaveView: string|boolean, the view file to show details of exported file link. This property will be validated only when stream is false and streamAfterSave 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.

  35. batchSize: int, 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.

  36. 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..

  37. 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

  38. 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

  39. 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

  40. 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

  41. 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

  42. 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

  43. docProperties: array, is the PHPExcel document properties

  44. pdfLibrary: string, is the library used to render the PDF when exporting as PDF. Defaults to 'mPDF'. Must be one of:

    • PHPExcel_Settings::PDF_RENDERER_TCPDF or tcPDF

    • PHPExcel_Settings::PDF_RENDERER_DOMPDF or DomPDF

    • PHPExcel_Settings::PDF_RENDERER_MPDF or mPDF

  45. pdfLibraryPath: string, is the alias for the pdf library path to export to PDF. Defaults to '@vendor/kartik-v/mpdf'. This must be set to one of the PDF libraries supported by PHP Excel.

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

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

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