Yii2: Export GridView

Export is not available from the built-in GridView widget.

However there’s an enhanced GridView widget that include this functionality, along with many other features missing from the built in widget.

Here’s an example of exporting data in the grid to CSV or Excel format. In view file:

use kartik\grid\GridView;
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'layout'        => "{summary}\n<div class=\"pull-right\">{toolbar}</div>\n{items}\n{pager}",
    'toolbar'       => [
        '{export}',
        '{toggleData}',
    ],
    'export'        => [
        'fontAwesome'       => true,
        'showConfirmAlert'  => false,
        'target'            => GridView::TARGET_BLANK,
    ],
    'exportConfig'  => [
        GridView::CSV => [],
        GridView::EXCEL => [],
    ],
    'columns' => [
        ....
    ],
]);

Notes:

  • Line 4: ‘layout’ attribute must be set, or the toolbar would not show up.
  • Lines 5: defines the buttons in the toolbar.
  • Line 6: {export} defines export button with drop down defined in ‘exportConfig’ attribute.
  • Line 7: {toggleData} defines button to toggle data for this page only or for all page..
  • Line 11: by default, a popup confirmation is displayed everytime data is exported. This is annoying and setting ‘showConfirmAlert’ to false stops this from happening.
  • Lines 14-16: config to export the current grid to CSV and Excel. Refer to document for other formats.

Leave a Reply

Your email address will not be published. Required fields are marked *