Yii2 gridview to excel

We will leverage Yii2-excelview widget. So, first of all is install Yii2-excelview:

Either run

php composer.phar require --prefer-dist arturoliveira/yii2-excelview "*"

or add

"arturoliveira/yii2-excelview": "*"

to the require section of your composer.json file.

In the main.php
add below if not exist before:

'modules' => [//add by Scott
        'gridview' => [
            'class' => 'kartikgridModule'
        // enter optional module parameters below - only if you need to  
        // use your own export download action or custom translation 
        // message source
        // 'downloadAction' => 'gridview/export/download',
        // 'i18n' => []
        ],
...

In your controller create an export action like below.
Then you can export your data through link: yousiteyourcontrollerexport

use arturoliveiraExcelView;
    public function actionExport() {
        $searchModel = new CountrySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        ExcelView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'fullExportType'=> 'xlsx', //can change to html,xls,csv and so on
            'grid_mode' => 'export',
            'columns' => [
                ['class' => 'yiigridSerialColumn'],
                'code',
                'name',
                'population',
              ],
        ]);
    }

Another more elegant way are below:

  1. Still create export action as above state.

  2. Change the default kartik-v export action to below

'modules' => [//add by Scott
        'gridview' => [
            'class' => 'kartikgridModule',
             // 'downloadAction' => 'gridview/export/download',
            'downloadAction' => 'export',  //change default download action to your own export action.
  1. Add below to your grid vidget:
'layout' => '{summary}<div class="pull-right">{export}&nbsp{fullexport}&nbsp</div><div>{items}</div>{pager}',
            'exportConfig' => [
                kartikgridGridView::EXCEL => ['label' => 'Export to Excel'],
            ],
            'fullExportConfig' => [
                ExcelView::FULL_EXCEL => [],
                //ExcelView::FULL_CSV => ['label' => 'Save as CSV'],
                ExcelView::FULL_HTML => [],
            ],

Btw, you better remove {fullexport} and ‘fullExportConfig’ session since it is for Excelview dropdown menu only.
And we try to leverage Kartik-v gridview dropdown menu, even we still use the Excelview export action. I intend list it just FYI.

Then when you click the export dropdown menu, it will auto invoke download action.

The reason I don’t use excelView {fullexport} directly is excelView dropdown menu have some bugs till Oct 24,2014. So I try combine Kartik-v’s export menu + ExcelView export function as tentative solution.

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

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

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

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

Are you struggling for exporting data to excel?

This tutorial will helpful to create your own extension for exporting data as excel from your gridview data. What you display in gridview (text), It will export as excel.

  1. Install PHP Excel
  2. Excel Gridview Class
  3. Gridview To Excel

Install PHP Excel In Yiiframework 2.0

Add below line in composer.json and update composer to install phpoffice excel.

require": {
    ......
    "phpoffice/phpexcel": "*"
    ......
}

Excel Gridview Class In Yiiframework 2.0

I created ‘ExcelGrid.php’ class from existing class on web and it is extending the basic GridView class.
First You have to download this class. Then add it in your application and change the namespace for this class (based on installation).

<?php
namespace appcomponents;

//namespace bsourcegridview;//in vendor folder
use Yii;
use Closure;
use yiii18nFormatter;

//..........

class ExcelGrid extends yiigridGridView
{
    //..........
    public static function columnName($index)
    {
        //..........
    }

    public function init()
    {
        parent::init();
    }

    public function run()
    {
        //..........
        parent::run();
    }

    public function init_provider()
    {
        //..........
    }

    public function init_excel_sheet()
    {
        //..........
    }

    public function initPHPExcelWriter($writer)
    {
        //..........
    }

    public function generateHeader()
    {
        //..........
    }

    public function generateBody()
    {
        //..........
    }

    public function generateRow($model, $key, $index)
    {
        //..........
    }

    public function getColumnHeader($col)
    {
        //..........
    }

    protected function setVisibleColumns()
    {
        //..........
    }

    protected function setHttpHeaders()
    {
        header("Cache-Control: no-cache");
        header("Expires: 0");
        header("Pragma: no-cache");
        header("Content-Type: application/{$this->extension}");
        header("Content-Disposition: attachment; filename={$this->filename}.{$this ->extension}");
    }
}
?>
Method 1:

Add this class in ‘project/components’ folder and defined namespace as

namespace appcomponents;
Method 2:

If would you like to add it in vendor folder, follow this method . First you have to creat a folder ‘bsource/gridview’ format and have to add this inside . Namespace like

 namespace bsource / gridview;

After created class, you have to autoload this class. Goto file

 'vendor/composer/autoload_psr4.php'

and add the below line in return array

'bsource\gridview\' => array( $vendorDir . '/bsource/gridview' ),

Gridview To Excel In Yiiframework 2.0

After completed above steps, Just you have to call ‘ExcelGrid’ widget using namespace to export data as excel in yii2 .

Excel.php
<?php
    // appcomponentsExcelGrid::widget([ OR
    bsourcegridviewExcelGrid::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        //'extension'=>'xlsx',
        //'filename'=>'excel',
        'properties' => [
            //'creator' =>'',
            //'title' => '',
            //'subject' => '',
            //'category' => '',
            //'keywords' => '',
            //'manager' => '',
            //'description'=>'BSOURCECODE',
            //'company' =>'BSOURCE',
        ],
        'columns' => [
            ['class' => 'yiigridSerialColumn'],
            'username',
            'createdby',
            'createdon',
        ],
    ]);
?>

Sample Controller . php

<?php
//............

class CategoryController extends Controller
{
    public function actionExcel()
    {
        $searchModel  = new categorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->renderPartial('excel', ['searchModel' => $searchModel,'dataProvider' => $dataProvider]);
    }

    public function actionIndex()
    {
        $searchModel  = new categorySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', ['searchModel' => $searchModel,'dataProvider' => $dataProvider]);
    }
    //............
}
?>

- !!! Library is deprecated !!!

Yii2 ExcelReport Extension

An extension for generate excel file from GridView content. When used with a GridView, extention saves the results of filtering and sorting in a file. Everything you see in the GridView will be imported into a file. All tasks are run in the background, the user can check the progress with the progressbar. It is not necessary to remain on the current page during the execution. You can continue working with the application. When the file is created, the download link will remain on the page with the widget until it is used, the user can use it at any time. When the file is downloaded, you can start generating a new report.

To run tasks in the background, the extension uses a queues.

Use the extension only makes sense to generate large files (> 50,000 lines).

Latest Stable Version
Total Downloads

Installation

The preferred way to install this extension is through composer.

Either run

php composer require --prefer-dist custom-it/yii2-excel-report

or add

"custom-it/yii2-excel-report": "*"

to the require section of your composer.json file.

Configuration

Before using the module, configure the queues

Add progress behavior to Queue configuration:

'queue' => [
    // ... you Queue configuration ...
    'as progress' => customitexcelreportProgressBehavior::class,
],

Usage

Once the extension is installed, simply use it in your code by :

$gridColumns = [
    ['class' => 'yiigridSerialColumn'],
    'id',
    'name',
    'date',
    'post',
    ['class' => 'yiigridActionColumn'],
];

// Render widget
echo customitexcelreportExcelReport::widget([
    'columns' => $gridColumns,
    'dataProvider' => $dataProvider,
]);

// Can be used with or without a GridView
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns
]);

Содержание

  1. kartik-v/yii2-export
  2. Sign In Required
  3. Launching GitHub Desktop
  4. Launching GitHub Desktop
  5. Launching Xcode
  6. Launching Visual Studio Code
  7. Latest commit
  8. Git stats
  9. Files
  10. README.md
  11. Name already in use
  12. yii2-export / README.md
  13. Yii2 gridview export excel
  14. Requirements ¶
  15. Installation ¶
  16. Usage ¶
  17. Resources ¶
  18. Related Extensions
  19. Bootstrap Info
  20. Global Bootstrap Version
  21. Yii2 Bootstrap Dependency
  22. Override Bootstrap CSS/JS
  23. Icons for Bootstrap
  24. Installation
  25. Composer Package Manager Recommended
  26. Manual Install
  27. Settings
  28. dataProvider
  29. columns
  30. emptyText
  31. target
  32. krajeeDialogSettings
  33. showConfirmAlert
  34. enableFormatter
  35. asDropdown
  36. dropdownOptions
  37. pjaxContainerId
  38. clearBuffers
  39. initProvider
  40. showColumnSelector
  41. columnSelector
  42. columnSelectorOptions
  43. columnSelectorMenuOptions
  44. columnBatchToggleSettings
  45. container
  46. template
  47. timeout
  48. selectedColumns
  49. disabledColumns
  50. hiddenColumns
  51. noExportColumns
  52. exportFormView
  53. exportColumnsView
  54. exportConfig
  55. exportRequestParam
  56. fontAwesome
  57. stripHtml
  58. styleOptions
  59. headerStyleOptions
  60. boxStyleOptions
  61. contentBefore
  62. contentAfter
  63. autoWidth
  64. encoding
  65. filename
  66. folder
  67. stream
  68. deleteAfterSave
  69. afterSaveView
  70. linkPath
  71. linkFileName
  72. batchSize
  73. messages
  74. onInitExcel
  75. onInitSheet
  76. onInitWriter
  77. onRenderHeaderCell
  78. onRenderDataCell
  79. onRenderFooterCell
  80. onRenderSheet
  81. onGenerateFile
  82. docProperties
  83. dynagrid
  84. dynagridOptions
  85. groupedRowStyle
  86. On Render Methods

kartik-v/yii2-export

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

yii2-export

A library to export server/db data in various formats (e.g. excel, html, pdf, csv etc.) using the PhpSpreadsheet library. The widget allows you to configure the dataProvider, columns just like a yiigridGridView. However, it just displays the export actions in form of a ButtonDropdown menu, for embedding into any of your GridView or other components.

In addition, with release v1.2.0, the extension also displays a handy grid columns selector for controlling the columns for export. The features available with the column selector are:

  • shows a column picker dropdown list to allow selection of columns for export.
  • new container property allows you to group the export menu and column selector dropdowns.
  • new template property for manipulating the display of menu, column selector or additional buttons in button group.
  • allows configuration of column picker dropdown button through columnSelectorOptions
  • auto-generates column labels in the column selector. But you can override displayed column labels for each column key through columnSelector property settings.
  • allows preselected columns through selectedColumns (you must set the selected column keys)
  • allows columns to be disabled in column selector through disabledColumns (you must set the disabled column keys)
  • allows columns to be hidden in column selector through hiddenColumns (you must set the hidden column keys)
  • allows columns to be hidden from both export and column selector through noExportColumns (you must set the no export column keys)
  • toggle display of the column selector through showColumnSelector property
  • column selector is displayed only if asDropdown is set to true .

The extension offers configurable user interfaces for advanced cases using view templates.

  • exportColumnsView allows you to setup your own custom view file for rendering the column selector dropdown.
  • afterSaveView allows you to setup your own after save view file if you are configuring to save exported file on server.

You can see detailed documentation and demonstration on usage of the extension.

NOTE: Refer the CHANGE LOG for details on changes to various releases.

The preferred way to install this extension is through composer.

Note: Read this web tip /wiki on setting the minimum-stability settings for your application’s composer.json.

Install the necessary pre-requisite (Krajee Dropdown Extension) based on your bootstrap version:

  • For Bootstrap v5.x install the extension kartik-v/yii2-bootstrap5-dropdown
  • For Bootstrap v4.x install the extension kartik-v/yii2-bootstrap4-dropdown
  • For Bootstrap v3.x install the extension kartik-v/yii2-dropdown-x

For example if you are using the Bootstrap v5.x add the following to the require section of your composer.json file:

to the require section of your composer.json file.

Note: you must run composer update to have the latest stable dependencies like kartik-v/yii2-krajee-base

The yii2-export extension is dependent on yii2-grid extension module. In order to start using yii2-export , you need to ensure setup of the gridview module in your application modules configuration file. For example:

This project exists thanks to all the people who contribute. [Contribute].

Become a financial contributor and help us sustain our community. [Contribute]

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

Источник

Name already in use

yii2-export / README.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

yii2-export

A library to export server/db data in various formats (e.g. excel, html, pdf, csv etc.) using the PhpSpreadsheet library. The widget allows you to configure the dataProvider, columns just like a yiigridGridView. However, it just displays the export actions in form of a ButtonDropdown menu, for embedding into any of your GridView or other components.

In addition, with release v1.2.0, the extension also displays a handy grid columns selector for controlling the columns for export. The features available with the column selector are:

  • shows a column picker dropdown list to allow selection of columns for export.
  • new container property allows you to group the export menu and column selector dropdowns.
  • new template property for manipulating the display of menu, column selector or additional buttons in button group.
  • allows configuration of column picker dropdown button through columnSelectorOptions
  • auto-generates column labels in the column selector. But you can override displayed column labels for each column key through columnSelector property settings.
  • allows preselected columns through selectedColumns (you must set the selected column keys)
  • allows columns to be disabled in column selector through disabledColumns (you must set the disabled column keys)
  • allows columns to be hidden in column selector through hiddenColumns (you must set the hidden column keys)
  • allows columns to be hidden from both export and column selector through noExportColumns (you must set the no export column keys)
  • toggle display of the column selector through showColumnSelector property
  • column selector is displayed only if asDropdown is set to true .

The extension offers configurable user interfaces for advanced cases using view templates.

  • exportColumnsView allows you to setup your own custom view file for rendering the column selector dropdown.
  • afterSaveView allows you to setup your own after save view file if you are configuring to save exported file on server.

You can see detailed documentation and demonstration on usage of the extension.

NOTE: Refer the CHANGE LOG for details on changes to various releases.

The preferred way to install this extension is through composer.

Note: Read this web tip /wiki on setting the minimum-stability settings for your application’s composer.json.

Install the necessary pre-requisite (Krajee Dropdown Extension) based on your bootstrap version:

  • For Bootstrap v5.x install the extension kartik-v/yii2-bootstrap5-dropdown
  • For Bootstrap v4.x install the extension kartik-v/yii2-bootstrap4-dropdown
  • For Bootstrap v3.x install the extension kartik-v/yii2-dropdown-x

For example if you are using the Bootstrap v5.x add the following to the require section of your composer.json file:

to the require section of your composer.json file.

Note: you must run composer update to have the latest stable dependencies like kartik-v/yii2-krajee-base

The yii2-export extension is dependent on yii2-grid extension module. In order to start using yii2-export , you need to ensure setup of the gridview module in your application modules configuration file. For example:

This project exists thanks to all the people who contribute. [Contribute].

Become a financial contributor and help us sustain our community. [Contribute]

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

Источник

Yii2 gridview export excel

This extension allows exporting of data from a yii2-grid This is a port to Yii2 of an extension already available for Yii1 eexcelview

Requirements ¶

  • Tested on Yii 2.0.0
  • Requires yii2-grid and phpoffice/phpexcel

Installation ¶

The preferred way to install this extension is through composer.

to the require section of your composer.json file.

Usage ¶

Once the extension is installed, simply use it in your code by :

To include the export buttons just add to your layout

All the yii2-grid options are available please refer to yii2-grid page for instructions

Since this module depends on yii2-grid don’t forget to add the following to your config file

Resources ¶

phpoffice/phexcel 1.8.0 => no matching package found.

I try both
php composer.phar require —prefer-dist arturoliveira/yii2-excelview «*»
and
php composer.phar require —prefer-dist arturoliveira/yii2-excelview «dev-master»

Find error:
phpoffice/phexcel 1.8.0 => no matching package found.
Can you advise? thanks.

Successful install extention now.

My original error is phpoffice/phpexcel 1.8.0 => no matching package found.
It can resolve by
remove phpoffice/phpexcel:»dev-master» from my existig composer.json firstly to avoid different version of phpexcel
then add
«arturoliveira/yii2-excelview»: «dev-master»
then
composer udpate —prefer-dist

Pay attention: Need add gridview in modules

Pay attention: Need add gridview in modules

Added to the instructions

issue: cannot ignore or direct export Action column

Getting unknown property: yiigridActionColumn::attribute

Another Issue: Include additional characters when export excel/csv.

It will normal if I export in control directly with ‘export’ mode instead of ‘grid’mode.
however, if I set layout as

and try export through the button, the export result will be not correct as below:
CSV:

Excel:
The excel output even cannot open normally, like below

I think it caused by additional character output when generate excel to cause format not correct. Thanks.

Third Issue: Cannot integrate into panel layout.

I can show fullexport in layout, however, it will not work in case I setup pane and define pane layout. Can you help to resolve it? thx.

Scott several issues

Sorry for the delay
Could you please create issues in the issue tracker with the description of your problems

how to export with filtered values

Suppose if the user is wants to export only the selected values using this extension , How to implement?

For Eg, if i want to download a report for filter using datewise given by user in the page.

Column format

I’m trying to add a column with format:

but it doesn’t work. datetime just is shown using default format Y-m-d h:i:s

Источник

Bootstrap Info

ExportMenu supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the ExportMenu::bsVersion property to one of the following.

To use with bootstrap 3 library — you can set ExportMenu::bsVersion property to any string starting with 3 (e.g. 3 or 3.3.7 or 3.x )

To use with bootstrap 4 library — you can set ExportMenu::bsVersion property to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x )

To use with bootstrap 5 library — you can set ExportMenu::bsVersion property to any string starting with 5 (e.g. 5 or 5.1.0 or 5.x )

Global Bootstrap Version

Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion property within Yii 2 application params (i.e. Yii::$app->params[‘bsVersion’] ). To set this up, add this section of code to your application params configuration file (e.g. config/params.php ):

If ExportMenu::bsVersion property is set, in addition to Yii::$app->params[‘bsVersion’] , the extension level setting ( ExportMenu::bsVersion property) will override the Yii::$app->params[‘bsVersion’] . If ExportMenu::bsVersion property is not set, and Yii::$app->params[‘bsVersion’] is also not set, ExportMenu::bsVersion property will default to 3.x (i.e. Bootstrap 3.x version will be assumed as default).

Yii2 Bootstrap Dependency

You need to install one of yiisoft/yii2-bootstrap or yiisoft/yii2-bootstrap4 or yiisoft/yii2-bootstrap5 extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion is set to 5.x and yiisoft/yii2-bootstrap5 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5 extension. If bsVersion is set to 4.x and yiisoft/yii2-bootstrap4 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4 extension. Similarly, if bsVersion is set to 3.x and yiisoft/yii2-bootstrap is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap extension.

To install yiisoft/yii2-bootstrap5 , add the repo to the require section of your application’s composer.json.

To install yiisoft/yii2-bootstrap4 , add the repo to the require section of your application’s composer.json.

To install yiisoft/yii2-bootstrap , add the repo to the require section of your application’s composer.json.

Override Bootstrap CSS/JS

The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:

yiibootstrapBootstrapAsset and/or yiibootstrapBootstrapPluginAsset for bootstrap 3.x ( bsVersion = 3 setting)

yiibootstrap4BootstrapAsset and/or yiibootstrap4BootstrapPluginAsset for bootstrap 4.x ( bsVersion = 4 setting)

yiibootstrap5BootstrapAsset and/or yiibootstrap5BootstrapPluginAsset for bootstrap 5.x ( bsVersion = 5 setting)

This is controlled by the property bsDependencyEnabled within the asset bundle (which defaults to true ). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:

Global Override: Set Yii::$app->params[‘bsDependencyEnabled’] to false in your Yii 2 application config params.php . This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.

Asset Bundle Specific Override: Set bsDependencyEnabled to false for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.

When setting bsDependencyEnabled to false , you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.

Icons for Bootstrap

Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.

For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD section of your view layout file, when bsVersion is set to 4.x or 5.x .

Option 1: Font CSS version of Font Awesome:

Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):

Alternatively, you can use the FontAwesomeAsset from the kartik-v/yii2-icons package to load the SVG/JS version.

Installation

The yii2-export extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended

Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-export via composer package manager. Either run:

to your application’s composer.json file.

Manual Install

You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

Settings

The Export Menu extends the kartikgridGridView 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

yiidataDataProviderInterface, is the data provider for the Export Menu. See yiigridGridView::dataProvider for more details.

columns

array, is the Grid column data configuration to be displayed in the Exported data output. See yiigridGridView::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 yiigridGridView::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-secondary btn-default’] . The following special options are available:

icon : string, label for the dropdown defaults to

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 yiibootstrapButtonDropdown 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 yiibootstrapButtonDropdown 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-secondary btn-default’] . The following special options are available:

icon : string, label for the dropdown defaults to

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 n

. The following tags will automatically be parsed and replaced:

: will be replaced with columns selector dropdown

: will be replaced with export menu dropdown

timeout

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 ‘Xls’

ExportMenu::FORMAT_EXCEL_X or ‘Xlsx’

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.

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 PHPSpreadsheet writer type.

options : array, HTML attributes for export menu item.

The exportConfig if not set will default to the following:

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.

stripHtml

boolean, whether to strip HTML tags from formatted content in each data cell before rendering the PhpSpreadsheet Cell. Defaults to true .

styleOptions

array, is the output style configuration options for each data cell setup as an associative array: $key => $setting . The $key must be one of ExportMenu::FORMAT_ constants. Note that one can also set the exportMenuStyle property for each grid column to format one’s style specific to the column (note that the column class must be kartikgridDataColumn or kartikgridSerialColumn ). The $setting must be the style configuration array as required by PHPSpreadsheet. This defaults to an empty array.

array, is the the output style configuration options for the header row setup as an associative array: $key => $setting . The $key must be one of ExportMenu::FORMAT_ constants. The $setting must be the style configuration array as required by PHPSpreadsheet. Note that one can also set the exportHeaderMenuStyle property for each grid column to format one’s header style specific to the column (note that the column class must be kartikgridDataColumn or kartikgridSerialColumn ). The following configuration is defaulted for headerStyleOptions :

boxStyleOptions

array, is the the output style configuration options for the entire spreadsheet data range box as an associative array: $key => $setting . The $key must be one of ExportMenu::FORMAT_ constants. The headerStyleOptions will be parsed and applied again after boxStyleOptions to ensure the header row box formatting is correct. The $setting must be the style configuration array as required by PHPSpreadsheet. The following configuration is defaulted for boxStyleOptions :

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

folder

string, the folder to save the exported file. Defaults to @app/runtime/export/ . If the specified folder does not exist, the extension will attempt to create it — else an exception will be thrown.

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 set to false . Note that the afterSaveView property 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. .

onInitExcel

Closure, is the callback function on initializing the PhpSpreadsheet library. The anonymous function should have the following signature:

sheet : PhpOfficePhpSpreadsheetWorksheetWorksheet, is the PHPSpreadsheet work sheet object instance

widget : ExportMenu, is the current ExportMenu object instance

onInitSheet

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

sheet : PhpOfficePhpSpreadsheetWorksheetWorksheet, is the PHPSpreadsheet work sheet object instance

widget : ExportMenu, is the current ExportMenu object instance

onInitWriter

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

writer : PhpOfficePhpSpreadsheetWriterBaseWriter, is the PHPSpreadsheet writer object instance

widget : ExportMenu, is the current ExportMenu object instance

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

cell : PhpOfficePhpSpreadsheetCellCell, is the PHPSpreadsheet cell object instance

content : string, is the header cell content being rendered

widget : ExportMenu, is the current ExportMenu 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:

cell : PhpOfficePhpSpreadsheetCellCell, is the PHPSpreadsheet 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

widget : ExportMenu, is the current ExportMenu object instance

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

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

cell : PhpOfficePhpSpreadsheetCellCell, is the PHPSpreadsheet work sheet object instance

content : string, is the footer cell content being rendered

widget : ExportMenu, is the current ExportMenu 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:

sheet : PhpOfficePhpSpreadsheetWorksheetWorksheet, is the PHPSpreadsheet work sheet object instance

widget : ExportMenu, is the current ExportMenu 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:

extension : string, is the currently exported file extension

widget : ExportMenu, is the current ExportMenu 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 PHPSpreadsheet document properties

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

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 kartikdynagridDynagrid 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:

groupedRowStyle

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

On Render Methods

The widget offers an event based approach to manipulate PHPSpreadsheet 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 $widget within each of the callbacks above. The following list of getters, setters, and methods could be accessible via the $widget object instance. Note that this list below is not comprehensive. All public properties and methods of ExportMenu should be accessible via the $widget object instance.

An example of configuring the onRenderSheet method could be:

Источник

Время на прочтение
3 мин

Количество просмотров 13K

Начало

Одна поддерживаемая нашей компанией учетно-отчетная система начала очень быстро разрастаться в количестве хранимых данных. Система написана на PHP с использованием фреймворка Yii2. Изначально отчеты строились через библиотеку PhpSpreadsheet, которая пришла на смену, уже давно ставшему deprecated, PhpExcel.

Среди разного вида отчетности был один очень крупный – фактически полный набор всех хранящихся в БД данных должен выгружаться в одну excel-таблицу. На начальном этапе проблем не возникало, но когда объем стал превышать многие сотни тысяч записей, то скрипт формирования выгрузки стал отваливаться в timeout limit. Для начала повысили этот самый лимит и начали искать пути решения проблемы. Но врЕменного решения хватило ненадолго – проблема с лимитом времени превратилась в проблему с лимитом памяти. Серверу накинули «оперативки» и вообще сняли memory_limit для данной отдельно взятой операции. Очень скоро пользователи снова начали жаловаться на ошибки по времени выполнения. Пришлось убрать и временной лимит для полного отчета. Но сидеть и смотреть десяток минут на экран с индикатором загрузки – мало удовольствия. К тому же иногда отчет нужен был «здесь и сейчас», и каждая потраченная минута на его формирование оказывалась критичной. Эксперименты с настройками окружения прекратили, почесали затылок и приступили к оптимизации кода.

Поиск решения

Первое, что было сделано – скрипт отчетности вынесен в фоновый процесс, а пользователь наблюдает за ходом через «прогрессбар». Фоновое выполнение заданий реализовали через механизм очередей с использованием Redis для хранения. Работа в системе не останавливается, можно заниматься другими задачами и периодически возвращаться на страницу с отчетом – посмотреть, а не готов ли файл. Как только файл формируется, пользователю предлагается ссылка на скачивание. Но, как уже упоминалось выше, иногда файл требовался «немедленно», а повышение юзабилити никак не решало эту проблему. Тем временем количество данных продолжало расти и время построения файла дошло до 79 минут! Это совершенно не приемлемо, особенно учитывая, что отчетность — одна из основ функционала данной системы. Нет, все остальные части работали как часы, но эта ложка дегтя портила общее впечатление.

Первые результаты

Снова сели за анализ кода. Первое, что было протестировано – процесс выбора данных из БД. Но запросы уже были оптимизированы максимально возможным способом. Хоть самый долгий запрос и представлял собой страшную выборку с пятью-шестью обращениями к монструозному ФИАСу, но отрабатывал за 2-5 секунд. Слабым местом был не он, а формирование файла-«эксельника». Начались попытки оптимизации этого процесса. Начиная от кеширования в redis, до извращений вроде формирования отдельных небольших «эксельников» в параллельных потоках с последующим склеиванием в один файл. Но результат был всегда один: проблема со временем превращалась в проблему с памятью и наоборот. Золотой середины не было, только перетекание из крайности в крайность. После определенного количества данных потребление ресурсов библиотекой начинало расти экспоненциально и победить это не представлялось возможным. PhpSpreadsheet – не подходит для больших файлов. В итоге было принято решение сменить библиотеку. Как вариант – написание своего аналога для формирования эксель-файлов.

Анализ и выбор инструмента

Спешить с написанием велосипедов не стали, а для начала провели аналитику существующих решений. Из возможных вариантов заинтересовал только box/spout. Быстро переписали модуль с использованием этой библиотеки. В итоге, полный отчет получился за 145 секунд. Напомню, что последние тесты с PhpSpreadsheet — 79 минут, а тут 2,5 минуты! Провели тестирование: увеличили объем данных в 2 раза. Отчет сформировался за 172 секунды. Разница потрясающая. Конечно, библиотека не обладает всеми теми же функциями, что и PhpSpreadsheet, но в данном случае хватает и минимального набора инструментов, так как критичным является скорость работы.

Расширение для Yii2

Итоговое решение оформили в виде расширения для Yii2. Может быть, кому-то пригодится. Расширение позволяет выгрузить любой набор данных из GridView в excel с сохранением фильтрации и сортировки. В качестве зависимостей использует yii/queue и box/spout. Применять расширение имеет смысл для формирования действительно больших файлов, ну, хотя бы 50 000 строк =) В данный момент модуль, ставший основой для расширения, лихо справляется с нагрузкой почти в 600 000 строк.

Ссылка на github: Yii2 ExcelReport Extension

Спасибо за внимание!

Bootstrap Info

ExportMenu supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the ExportMenu::bsVersion property to one of the following.

  • To use with bootstrap 3 library — you can set ExportMenu::bsVersion property to any string starting with 3 (e.g. 3 or 3.3.7 or 3.x)

  • To use with bootstrap 4 library — you can set ExportMenu::bsVersion property to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

  • To use with bootstrap 5 library — you can set ExportMenu::bsVersion property to any string starting with 5 (e.g. 5 or 5.1.0 or 5.x)

The following sections describe the pre-requisites for enabling Bootstrap library specific version support in your application and other related controls/overrides.

Global Bootstrap Version


Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']). To set this up, add this section of code to your application params configuration file (e.g. config/params.php):

'params' => [
    'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions
    // other settings
    // 'adminEmail' => 'admin@example.com'
]

If ExportMenu::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (ExportMenu::bsVersion property) will override the Yii::$app->params['bsVersion']. If ExportMenu::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, ExportMenu::bsVersion property will default to 3.x (i.e. Bootstrap 3.x version will be assumed as default).

Yii2 Bootstrap Dependency


You need to install one of yiisoft/yii2-bootstrap or yiisoft/yii2-bootstrap4 or yiisoft/yii2-bootstrap5 extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion is set to 5.x and yiisoft/yii2-bootstrap5 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5 extension. If bsVersion is set to 4.x and yiisoft/yii2-bootstrap4 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4 extension. Similarly, if bsVersion is set to 3.x and yiisoft/yii2-bootstrap is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap extension.

To install yiisoft/yii2-bootstrap5, add the repo to the require section of your application’s composer.json.

"yiisoft/yii2-bootstrap5": "@dev"

To install yiisoft/yii2-bootstrap4, add the repo to the require section of your application’s composer.json.

"yiisoft/yii2-bootstrap4": "@dev"

To install yiisoft/yii2-bootstrap, add the repo to the require section of your application’s composer.json.

"yiisoft/yii2-bootstrap": "@dev"

Override Bootstrap CSS/JS


The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:

  • yiibootstrapBootstrapAsset and/or yiibootstrapBootstrapPluginAsset for bootstrap 3.x (bsVersion = 3 setting)

  • yiibootstrap4BootstrapAsset and/or yiibootstrap4BootstrapPluginAsset for bootstrap 4.x ( bsVersion = 4 setting)

  • yiibootstrap5BootstrapAsset and/or yiibootstrap5BootstrapPluginAsset for bootstrap 5.x (bsVersion = 5 setting)

This is controlled by the property bsDependencyEnabled within the asset bundle (which defaults to true). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:

  • Global Override: Set Yii::$app->params['bsDependencyEnabled'] to false in your Yii 2 application config params.php. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.

    'params' => [
        'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions
        // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets
        //
        // other params settings below
        // 'bsVersion' => '5.x',
        // 'adminEmail' => 'admin@example.com'
    ]
    
  • Asset Bundle Specific Override: Set bsDependencyEnabled to false for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.

    // ...
    'components' => [
        'assetManager' => [
            'bundles' => [
                'kartikformActiveFormAsset' => [
                    'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle
                ],
            ],
        ],
    ],
    

Note

When setting bsDependencyEnabled to false, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.

Icons for Bootstrap


Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.

For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD section of your view layout file, when bsVersion is set to 4.x or 5.x.

  • Option 1: Font CSS version of Font Awesome:

    <!-- on your view layout file HEAD section -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    
  • Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):

    <!-- on your view layout file HEAD section -->
    <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
    

    Alternatively, you can use the FontAwesomeAsset from the kartik-v/yii2-icons package to load the SVG/JS version.

    // on your view layout file
    use kartikiconsFontAwesomeAsset;
    FontAwesomeAsset::register($this);
    

Installation

The yii2-export extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-export via composer package manager. Either run:

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

or add:

"kartik-v/yii2-export": "dev-master"

to your application’s composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source

ZIP

or

TAR

ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.


Settings

The Export Menu extends the kartikgridGridView 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:


columns

array, is the Grid column data configuration to be displayed in the Exported data output. See yiigridGridView::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 yiigridGridView::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-secondary btn-default'].
The following special options are available:

  • icon: string, label for the dropdown defaults to <i class="fas fa-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 yiibootstrapButtonDropdown 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 yiibootstrapButtonDropdown 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-secondary btn-default'].
The following special options are available:

  • icon: string, label for the dropdown defaults to <i class="fas fa-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 'Xls'

  • ExportMenu::FORMAT_EXCEL_X or 'Xlsx'

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 PHPSpreadsheet 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' => ExportMenu::FORMAT_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' => ExportMenu::FORMAT_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' => ExportMenu::FORMAT_TEXT
    ],
    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' => ExportMenu::FORMAT_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' => ExportMenu::FORMAT_EXCEL
    ],
    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' => ExportMenu::FORMAT_EXCEL_X
    ],
]

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.

stripHtml

boolean, whether to strip HTML tags from formatted content in each data cell before rendering the PhpSpreadsheet Cell. Defaults to true.

styleOptions

array, is the output style configuration options for each data cell setup as an associative array: $key => $setting. The $key must be one of ExportMenu::FORMAT_ constants. Note that one can also set the exportMenuStyle property for each grid column to format one’s style specific to the column (note that the column class must be kartikgridDataColumn or kartikgridSerialColumn). The $setting must be the style configuration
array as required by PHPSpreadsheet. This defaults to an empty array.

headerStyleOptions

array, is the the output style configuration options for the header row setup as an associative array: $key => $setting. The $key must be one of ExportMenu::FORMAT_ constants. The $setting must be the style configuration
array as required by PHPSpreadsheet. Note that one can also set the exportHeaderMenuStyle property for each grid column to format one’s header style specific to the column (note that the column class must be kartikgridDataColumn or kartikgridSerialColumn). The following configuration is defaulted for headerStyleOptions:

[
    ExportMenu::FORMAT_HTML => $defaultStyle,
    ExportMenu::FORMAT_PDF => $defaultStyle,
    ExportMenu::FORMAT_EXCEL => $defaultStyle,
    ExportMenu::FORMAT_EXCEL_X => $defaultStyle,
]
// where $defaultStyle is set as below
$defaultStyle = [
    'font' => ['bold' => true],
    'fill' => [
        'fillType' => Fill::FILL_SOLID,
        'color' => [
            'argb' => 'FFE5E5E5',
        ],
    ],
    'borders' => [
        'outline' => [
            'borderStyle' => Border::BORDER_MEDIUM,
            'color' => ['argb' => Color::COLOR_BLACK],
        ],
        'inside' => [
            'borderStyle' => Border::BORDER_THIN,
            'color' => ['argb' => Color::COLOR_BLACK],
        ]
    ],
];

boxStyleOptions

array, is the the output style configuration options for the entire spreadsheet data range box as an associative array: $key => $setting. The $key must be one of ExportMenu::FORMAT_ constants. The headerStyleOptions will be parsed and applied
again after boxStyleOptions to ensure the header row box formatting is correct. The $setting must be the style configuration array as required by PHPSpreadsheet. The following configuration is defaulted for boxStyleOptions:

[
    ExportMenu::FORMAT_HTML => $defaultStyle,
    ExportMenu::FORMAT_PDF => $defaultStyle,
    ExportMenu::FORMAT_EXCEL => $defaultStyle,
    ExportMenu::FORMAT_EXCEL_X => $defaultStyle,
]
// where $defaultStyle is set as below
$defaultStyle = [
    'borders' => [
        'outline' => [
            'borderStyle' => Border::BORDER_MEDIUM,
            'color' => ['argb' => Color::COLOR_BLACK],
        ],
        'inside' => [
            'borderStyle' => Border::BORDER_DOTTED,
            'color' => ['argb' => Color::COLOR_BLACK],
        ]
    ],
];

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

folder

string, the folder to save the exported file. Defaults to @app/runtime/export/. If
the specified folder does not exist, the extension will attempt to create it — else an exception will be thrown.

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 set to false. Note that the
afterSaveView property 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..

onInitExcel

Closure, is the callback function on initializing the PhpSpreadsheet library. The anonymous function should have the following signature:

function ($sheet, $widget)

where:

  • sheet: PhpOfficePhpSpreadsheetWorksheetWorksheet, is the PHPSpreadsheet work sheet object instance

  • widget: ExportMenu, is the current ExportMenu 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, $widget)

where:

  • sheet: PhpOfficePhpSpreadsheetWorksheetWorksheet, is the PHPSpreadsheet work sheet object instance

  • widget: ExportMenu, is the current ExportMenu object instance

onInitWriter

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

function ($writer, $widget)

where:

  • writer: PhpOfficePhpSpreadsheetWriterBaseWriter, is the PHPSpreadsheet writer object instance

  • widget: ExportMenu, is the current ExportMenu 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, $widget)

where:

  • cell: PhpOfficePhpSpreadsheetCellCell, is the PHPSpreadsheet cell object instance

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

  • widget: ExportMenu, is the current ExportMenu 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, $widget)

where:

  • cell: PhpOfficePhpSpreadsheetCellCell, is the PHPSpreadsheet 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

  • widget: ExportMenu, is the current ExportMenu 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, $widget)

where:

  • cell: PhpOfficePhpSpreadsheetCellCell, is the PHPSpreadsheet work sheet object instance

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

  • widget: ExportMenu, is the current ExportMenu 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, $widget)

where:

  • sheet: PhpOfficePhpSpreadsheetWorksheetWorksheet, is the PHPSpreadsheet work sheet object instance

  • widget: ExportMenu, is the current ExportMenu 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, $widget)

where:

  • extension: string, is the currently exported file extension

  • widget: ExportMenu, is the current ExportMenu 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 PHPSpreadsheet document properties

i18n

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

[
    'class' => 'yiii18nPhpMessageSource',
    '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 kartikdynagridDynagrid 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 PHPSpreadsheet style configuration for a grouped grid row. Defaults to:

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


On Render Methods

The widget offers an event based approach to manipulate PHPSpreadsheet 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

  • onRenderHeaderCell

  • onRenderDataCell

  • onRenderFooterCell

  • onRenderSheet

  • onGenerateFile

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

// getters
$widget->getPHPSpreadsheet(); // returns PHPSpreadsheet object instance
$widget->getPHPSpreadsheetWriter();  // returns PHPSpreadsheet Writer object instance
$widget->getPHPSpreadsheetSheet();  // returns PHPSpreadsheet Sheet object instance
$widget->getExportType(); // returns the currently selected export type

// setters
$widget->setPHPSpreadsheet($obj); // sets/overwrites the PHPSpreadsheet object
$widget->setPHPSpreadsheetWriter($obj); // sets/overwrites the PHPSpreadsheet Writer object
$widget->setPHPSpreadsheetSheet($obj); // sets/overwrites the PHPSpreadsheet Sheet object

// other methods - check the ExportMenu source for public methods and properties
$widget->destroyPHPSpreadsheet(); // destroys the current PHPSpreadsheet object

An example of configuring the onRenderSheet method could be:

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


License

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

An extension for generate excel file from GridView content

  • dev-master

  • 1.0.1

  • 1.0.0

This package is not auto-updated.

Last update: 2023-04-01 22:01:44 UTC


README

- !!! Library is deprecated !!!

31646762?s=200&v=4

Yii2 ExcelReport Extension

An extension for generate excel file from GridView content. When used with a GridView, extention saves the results of filtering and sorting in a file. Everything you see in the GridView will be imported into a file. All tasks are run in the background, the user can check the progress with the progressbar. It is not necessary to remain on the current page during the execution. You can continue working with the application. When the file is created, the download link will remain on the page with the widget until it is used, the user can use it at any time. When the file is downloaded, you can start generating a new report.

To run tasks in the background, the extension uses a queues.

Use the extension only makes sense to generate large files (> 50,000 lines).

Latest Stable Version
Total Downloads

Installation

The preferred way to install this extension is through composer.

Either run

php composer require --prefer-dist custom-it/yii2-excel-report

or add

"custom-it/yii2-excel-report": "*"

to the require section of your composer.json file.

Configuration

Before using the module, configure the queues

Add progress behavior to Queue configuration:

'queue' => [
    // ... you Queue configuration ...
    'as progress' => customitexcelreportProgressBehavior::class,
],

Usage

Once the extension is installed, simply use it in your code by :

$gridColumns = [
    ['class' => 'yiigridSerialColumn'],
    'id',
    'name',
    'date',
    'post',
    ['class' => 'yiigridActionColumn'],
];

// Render widget
echo customitexcelreportExcelReport::widget([
    'columns' => $gridColumns,
    'dataProvider' => $dataProvider,
]);

// Can be used with or without a GridView
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => $gridColumns
]);

Miracle633

Сообщения: 13
Зарегистрирован: 2016.12.15, 09:26

Экпорт данных в файл(excel,pdf,etc.)

Всем Доброго Дня! Хотелось бы узнать Ваши советы на мои вопросы.
1) Как мне лучше вывести данные на страницу если они будут состоять из 50! столбцов. При этом надо будет сделать экспорт этих столбцов в файл (excel, pdf).
2) Если вывести на страницу всего 7-8 столбцов из 50. Можно ли будет сделать экспорт не только 7-8 столбцов, а всех 50?
Предпочтительнее, конечно, если будет совет на 2 вопрос. Буду признателен за любую информацию.

Аватара пользователя

Alexum

Сообщения: 683
Зарегистрирован: 2016.09.26, 10:00

Re: Экпорт данных в файл(excel,pdf,etc.)

Сообщение

Alexum » 2017.01.16, 09:34

Miracle633 писал(а): ↑2017.01.16, 09:09
1) Как мне лучше вывести данные на страницу если они будут состоять из 50! столбцов. При этом надо будет сделать экспорт этих столбцов в файл (excel, pdf).

Выводите виджетом GridView, тут сложно что-то другое посоветовать.

Готовое для экспорта.

Поскольку библиотеки разные при экспорте используются, то и проблемы вас ждут соответствующие:
Отдельное расширение yii2 Export Menu http://demos.krajee.com/export — неплохо в Excel, криво в PDF
Замена стандартному GridVIew http://demos.krajee.com/grid — криво в Excel, неплохо в PDF

с 50 столбцами гарантированно придётся горизонтально скроллить страницу. Целую страницу скроллить или только div с таблицей — по вкусу. В GridView от kartik по-умолчанию скроллится сам div.

Miracle633 писал(а): ↑2017.01.16, 09:09
2) Если вывести на страницу всего 7-8 столбцов из 50. Можно ли будет сделать экспорт не только 7-8 столбцов, а всех 50?
Предпочтительнее, конечно, если будет совет на 2 вопрос. Буду признателен за любую информацию.

Лично я использую Export Menu. Для него и GridView можно использовать один и тот же DataProvider, но указывать разный набор колонок. Соберёте массив columns для GridView из 8 столбцов, для ExportMenu из 50 и будет вам счастье.

Miracle633

Сообщения: 13
Зарегистрирован: 2016.12.15, 09:26

Re: Экпорт данных в файл(excel,pdf,etc.)

Сообщение

Miracle633 » 2017.01.16, 09:39

Alexum писал(а): ↑2017.01.16, 09:34
Лично я использую Export Menu. Для него и GridView можно использовать один и тот же DataProvider, но указывать разный набор колонок. Соберёте массив columns для GridView из 8 столбцов, для ExportMenu из 50 и будет вам счастье.

Спасибо, Добрый Человек! попробую второе и отпишусь)

Miracle633

Сообщения: 13
Зарегистрирован: 2016.12.15, 09:26

Re: Экпорт данных в файл(excel,pdf,etc.)

Сообщение

Miracle633 » 2017.01.16, 13:07

Alexum писал(а): ↑2017.01.16, 09:34
Лично я использую Export Menu. Для него и GridView можно использовать один и тот же DataProvider, но указывать разный набор колонок. Соберёте массив columns для GridView из 8 столбцов, для ExportMenu из 50 и будет вам счастье.

Забыл уточнить, что у меня таблица с большими данными (порядка 23000 строк, количество столбцов я указывал). Поэтому выдает ошибку. PHP Fatal Error — yiibaseErrorException Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes).
Как решить проблему?

Miracle633

Сообщения: 13
Зарегистрирован: 2016.12.15, 09:26

Re: Экпорт данных в файл(excel,pdf,etc.)

Сообщение

Miracle633 » 2017.01.16, 14:59

ElisDN писал(а): ↑2017.01.16, 13:22
Либо повысить memory_limit, либо экспортировать только в лёгкий CSV.

Постараюсь дать больше памяти.
Оффтоп: Я чуть со стула не упал когда увидел, что Вы ответили. В данное время смотрю Ваши вебинары, которые в открытом доступе. Очень познавательно. Спасибо

Аватара пользователя

Alexum

Сообщения: 683
Зарегистрирован: 2016.09.26, 10:00

Re: Экпорт данных в файл(excel,pdf,etc.)

Сообщение

Alexum » 2017.01.16, 15:47

Miracle633 писал(а): ↑2017.01.16, 14:59

ElisDN писал(а): ↑2017.01.16, 13:22
Либо повысить memory_limit, либо экспортировать только в лёгкий CSV.

Постараюсь дать больше памяти.
Оффтоп: Я чуть со стула не упал когда увидел, что Вы ответили. В данное время смотрю Ваши вебинары, которые в открытом доступе. Очень познавательно. Спасибо

PHPExcel ещё тот «убийца» памяти. ~1кб на 1 ячейку.

Дмитрий тут часто появляется, Мировой человек! Помню ещё по почте ему докучал :lol:, правда с последней моей проблемой так и не помог :cry: . А потом я открыл для себя этот форум, очень много полезного тут можно подчерпнуть.

Miracle633

Сообщения: 13
Зарегистрирован: 2016.12.15, 09:26

Re: Экпорт данных в файл(excel,pdf,etc.)

Сообщение

Miracle633 » 2017.01.16, 16:08

Alexum писал(а): ↑2017.01.16, 15:47
PHPExcel ещё тот «убийца» памяти. ~1кб на 1 ячейку.

Это правда? :shock: Я тут посчитал, что мой выходной excel файл будет хранить ~758000 ячеек. Что мне посоветуете сделать?

Alexum писал(а): ↑2017.01.16, 15:47
А потом я открыл для себя этот форум, очень много полезного тут можно подчерпнуть.

Согласен)

hi all i faced problems here

after i find a way to retrieve id data from gridview, now my problem is export the data to excel. here is my code in controller

public function actionCetakdispo()
{

$selection=(array)Yii::$app->request->post('selection');    
$template = Yii::getAlias("@webroot") . "/template/dispo.xlsx";
$spreadsheet = PhpOfficePhpSpreadsheetIOFactory::load($template);
$worksheet = $spreadsheet->getActiveSheet();//typecasting
foreach($selection as $id){
    $suratmasuks = Smwp::findOne((int)$id);        
    $baserow = 5;
    $no = 1;
    foreach($suratmasuks as $suratmasuk){
        $row = $no + $baserow;
        $worksheet->getCell('A'. $row)->setValue($no);
        $worksheet->getCell('B'. $row)->setValue($suratmasuk->jenis_surat);
        $worksheet->getCell('C'. $row)->setValue($suratmasuk->perihal);
        $no++;
    }

}
$writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, 'Xlsx');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="dispo.xlsx"');
header('Cache-Control: max-age=0');
Yii::$app->session->setFlash('success', 'berhasil download!');
$writer->save('php://output');      
exit;
}

its show an error : Trying to get property ‘jenis_surat’ of non-object. if i print_r($surat_masuks), its show like this :

appmodelsSmWp Object (
  [_attributes:yiidbBaseActiveRecord:private] => Array (
    [id] => 4
    [id_mfwp] => 1
    [id_user] => 3
    [tgl_surat] => 2019-10-08 00:00:00
    [tgl_terima] => 2019-10-15 00:00:00
    [tgl_cetak] => 2019-10-14 00:00:00
    [nomor_surat] => kksksk
    [no_agenda] => 992929
    [jenis_surat] => 3
    [perihal] => balasan surat kami
    [lokasi_scan] => 
    [ket_dispo] => kerjakan
    [index_cetak_dispo] => 0
    [index_cetak_reg] => 0
  )
  [_oldAttributes:yiidbBaseActiveRecord:private] => Array (
    [id] => 4
    [id_mfwp] => 1
    [id_user] => 3
    [tgl_surat] => 2019-10-08 00:00:00
    [tgl_terima] => 2019-10-15 00:00:00
    [tgl_cetak] => 2019-10-14 00:00:00
    [nomor_surat] => kksksk
    [no_agenda] => 992929
    [jenis_surat] => 3
    [perihal] => balasan surat kami
    [lokasi_scan] => 
    [ket_dispo] => kerjakan
    [index_cetak_dispo] => 0
    [index_cetak_reg] => 0
  )
  [_related:yiidbBaseActiveRecord:private] => Array ( ) 
  [_relationsDependencies:yiidbBaseActiveRecord:private] => Array ( ) 
  [_errors:yiibaseModel:private] => 
  [_validators:yiibaseModel:private] => 
  [_scenario:yiibaseModel:private] => default 
  [_events:yiibaseComponent:private] => Array ( ) 
  [_eventWildcards:yiibaseComponent:private] => Array ( ) 
  [_behaviors:yiibaseComponent:private] => Array ( )
) 

thx for explanation..

Edit : this is my gridview code

    <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,

    'columns' => [
        ['class' => 'yiigridSerialColumn',],
        'id',
        'kategori',
        'nama_wp',
        'nama',             
        'nomor_surat', 
        'tgl_surat',
        'perihal',
        'ket',
        ['class' => 'yiigridCheckboxColumn', 'checkboxOptions' => function($model, $key, $index, $widget) {
            return ['value' => $model['id'] ];
         },],
    ],
    ]); ?>

Like this post? Please share to your friends:
  • Xml шаблон для excel
  • Xml что бы читал excel
  • Xml формат для excel
  • Xml теги для word
  • Xml таблица для excel