Code Monkey home page Code Monkey logo

yii2-excelexport's Introduction

Yii2 Excel Export

Latest Stable Version Total Downloads Latest Unstable Version License

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

Features

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

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

Installation

Install the package with composer:

composer require codemix/yii2-excelexport

Quickstart example

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

Find more examples below.

Configuration and Use

ExcelFile

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

ExcelSheet

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

ActiveExcelSheet

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

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

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

Examples

ActiveQuery results

<?php
$file = \Yii::createObject([
    'class' => 'codemix\excelexport\ExcelFile',

    'writerClass' => '\PhpOffice\PhpSpreadsheet\Writer\Xls', // Override default of `\PhpOffice\PhpSpreadsheet\Writer\Xlsx`

    'sheets' => [

        'Active Users' => [
            'class' => 'codemix\excelexport\ActiveExcelSheet',
            'query' => User::find()->where(['active' => true]),

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

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

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

Raw data

<?php
$file = \Yii::createObject([
    'class' => 'codemix\excelexport\ExcelFile',
    'sheets' => [

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

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

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

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

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

Query builder results

<?php
$file = \Yii::createObject([
    'class' => 'codemix\excelexport\ExcelFile',
    'sheets' => [

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

Styling

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

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

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

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

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

<?php
$file = \Yii::createObject([
    'class' => 'codemix\excelexport\ExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemix\excelexport\ActiveExcelSheet',
            'query' => User::find(),
            'callbacks' => [
                // $cell is a \PhpOffice\PhpSpreadsheet\Cell object
                'A' => function ($cell, $row, $column) {
                    $cell->getStyle()->applyFromArray([
                        'font' => [
                            'bold' => true,
                        ],
                        'alignment' => [
                            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT,
                        ],
                        'borders' => [
                            'top' => [
                                'style' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                            ],
                        ],
                        'fill' => [
                            'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR,
                            'rotation' => 90,
                            'startColor' => [
                                'argb' => 'FFA0A0A0',
                            ],
                            'endColor' => [
                                'argb' => 'FFFFFFFF',
                            ],
                        ],
                    ]);
                },
            ],
        ],
    ],
]);

Events

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

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

yii2-excelexport's People

Contributors

devop1 avatar mikehaertl avatar mohammadyna avatar pana1990 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-excelexport's Issues

I can't install this components via composer

I got this following error message when I tried to install it via composer

[InvalidArgumentException]
Could not find package yii.bat at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

screenshot from 2016-09-17 23 02 52
How do I suppose to install it ?

Character encoiding issue on server

The excel file has been exported on my localhost successfully, but its not working on server. On server, a corrupted excel sheet is getting generated with character encoding problem. I am simply exporting with this line of code.
$file = \Yii::createObject([
'class' => 'codemix\excelexport\ExcelFile',
'sheets' => [
$sheetTitle => [ // Name of the excel sheet
'data' => $exportData,
'titles' => $titles,
]
]
]);
$file->send($sheetTitle.'.xlsx');
exit;

I think there is some misconfiguration on server, but not sure what the problem is. I have PHP7.2 installed on my server.

Below is the output that is being generated when i export file.

PK������mrNG�D�X����[Content_Types].xml��MN�0���"��%nY ��vAa �(�0��ؖg�w{&i���@�nbE�{��y��d۸l

m��������X�(���)�����F���;@1�_������c)j�x/%����E��y�
�QĿi!��K�y3��J�<���Z�1��0?Y��L%zV
c��Ib7������a/l٥P1:��q�r���j���j0A������u�"��"����(� �����W�M��)Tj�({ܲ�>���O���,X٭���>B��~׭� ��Ӥ6�J=�oBZ����t��X4��Cg�,���Qg�mr�L����ٯc�e��t� Z�?����hPv��±��u�j�<R�����}�Cv����PK������mrN��78�K��_rels/.rels���j�0 ��{
�{���1F�^ʠ�2���l�$���-}�y�����Î��O��v�y��;�؋Ӱ.JP��޵�^������Y�ű�3G�Ww�g�)���>� qQC���D���b!�]�i$L��3��� �2n����o�T��:Z
�h����[��4�ი��]���yN�,ە��>�>��j

Thanks

Write based common array

Can you provide me how to use this awesome extension if I have an array like this 👍
` Array
(
[0] => Array
(
[karyawan_id] => 2
[nama_karyawan] => Rizal
[nama_item] => Gunting Wanita
[harga] => 75,000.00
[persen_komisi] => 40
[amount_komisi] => 30,000.00
[counting] => 2
[total_item] => 150000
[total_komisi_karyawan] => 60,000.00
[total_omset] => 150,000.00
)

[1] => Array
    (
        [karyawan_id] => 2
        [nama_karyawan] => Rizal
        [nama_item] => Gunting Pria
        [harga] => 70,000.00
        [persen_komisi] => 50
        [amount_komisi] => 35,000.00
        [counting] => 
        [total_item] => 
        [total_komisi_karyawan] => 
        [total_omset] => 
    )

[2] => Array
    (
        [karyawan_id] => 2
        [nama_karyawan] => Rizal
        [nama_item] => Gunting Poni
        [harga] => 20,000.00
        [persen_komisi] => 80
        [amount_komisi] => 16,000.00
        [counting] => 1
        [total_item] => 20000
        [total_komisi_karyawan] => 16,000.00
        [total_omset] => 20,000.00
    )

)`

For the help, it so appreciated

Related table not printing

Hello,
I am try to export related contents, but files are empty.

Where I am wrong?

below my code,
Thanks

$query = Participants::find()
                ->where("participants.documents_id = :id", [":id" => $id]);

$model = $this->findModel($id);

$file = \Yii::createObject([
            'class' => 'codemix\excelexport\ExcelFile',
            'sheets' => [
                $model->title => [
                    'attributes' => [
                        'profile.name',
                        'profile.surname',
                        'profile.phone',
                        'profile.nationality',
                    ],
                    'class' => 'codemix\excelexport\ActiveExcelSheet',
                    'query' => $query,
                    'titles' => ['Nome', 'Cognome', 'Telefono', 'Nazionalità'],
                ]
            ]
        ]);

// and here my relations

public function getProfile()
    {
        return $this->hasMany(\dektrium\user\models\Profile::className(), ['user_id' => 'user_id']);
    }

not redirecting

i want to export some data as a file and then redirect to the main page:

$file = \Yii::createObject([
'class' => 'codemix\excelexport\ExcelFile',
'sheets' => [

                    'sheet1' => [
                        'data' => $active_codes,
                        
                        'titles' => [
                            'Activation Code'
                        ],
                    ],
                ]
            ]);

            $file->send('export.xlsx');
            
            return $this->redirect(['index']);

file is downloaded, but after that, page is not redirected.

Can't Export to excel

I have problem with export to excel. It's show somthing. Please see sample below.
Sample
|
|
/
" PK����Q#LG�D�X����[Content_Types].xml��MN�0����"��%nY ��vAa �(�0����ؖg�w{&i���@�nbE�{��y��d۸l m��������X�(���)�����F���;@1�_������c)j�x/%����E��y� �QĿi!��K�y3��J�<���Z�1��0?Y��L%zV c��Ib7�������a/l٥P1:��q�r���j���j0A������u�"��"����(� �����W�M��)Tj�({ܲ�>���O���,X٭���>B��~׭� ��Ӥ6�J=�oBZ����t��X4���Cg�,���Qg�mr�L����ٯc�e��t�� Z�?����hPv��±���u�j���R������}�Cv����PK����Q#L��78�K��_rels/.rels���j�0 ��{ �{���1F�^ʠ�2���l�$���-}�y�����Î��O��v�y��;�؋Ӱ.JP��޵�^������Y�ű�3G�Ww�g�)���>� qQC���D�� "

[Bug] "Using $this when not in object context" when i use related model

I get the following error "Using $this when not in object context" when i use related model.

Example code :

$file = \Yii::createObject([
                'class' => ExcelFile::class,
                'sheets' => [
                    'MoneyMovements' => [
                        'class' => ActiveExcelSheet::class,
                        'query' => User::find(),
                        'attributes' => [
                            'id',
                            'address.street', // related model
                        ],
                    ],
                ],
            ]);

screenshot_1

Can not use attributes defined by a getter

When listing an attribute name that corresponds to a getter function (e.g. fullName defined by getFullName()) in an ActiveExcelSheet it will throw an "Undefined Index" exception.

Add custom column to file

I want to understand how i can add some attribute to excell file, which out of columns from db. I have db with columns: ID, NAME, CAR. So when i create a file this columns will be my attributes. And i want to add some attribute, like PRICE, but it just a $price = "price"; . Help please

Cant create excel from data

I try put data that i already have after db query (because if i put Query instead of data - it does not work - it
does not calling '->all()' in your Sheet) as in your example.

$rows = TableName::find()->where("condition")->all();
$file = \Yii::createObject([
                'class' => 'codemix\excelexport\ExcelFile',
                'sheets' => [
                    'Users' => [
                        'data' => $rows],
                ]
            ]);
$file->saveAs($fileName);

And it throw error. What i do wrong?

Implement ability to apply data from array

With large amount of data, in my case its 30 sheets with about 1000 rows and 80 columns. The time to generate excel file is huge. I investigated that time can be twice faster if use method fromArray. Lets add parameter insertRawData. If insertRawData true then add data to sheets by fromArray method.
In model:

    $file = \Yii::createObject([
        'class' => 'codemix\excelexport\ExcelFile',
        'insertRawData' => true,
        'sheets' => $sheetsData
    ]);

Also about styles like: callbacks, format , formatters and types. In order to apply style lets add additional parameter stylesRules for each sheet. It can be applied to sheet by applyFromArray method.
For example:

        $sheetsData["sheet title"] = [
            'data' => $data,
            'stylesRules' => [
                'A1:Z1000' => [
                    'font' => [
                        'bold' => true,
                        'color' => ['rgb' => 'FF0000'],
                        'size' => 15,
                        'name' => 'Verdana'
                    ]
                ]
            ]
        ];

And in ExcelSheet:

/**
 * Render the data for hole sheet
 */
protected function renderSheet()
{
    $this->_sheet->fromArray($this->getData());
    $stylesRules = $this->getStylesRules();
    foreach ($stylesRules as $range => $rule) {
        $this->_sheet->getStyle($range)->applyFromArray($rule);
    }
}

public function getStylesRules()
{
    return $this->_stylesRules;
}

public function setStylesRules(array $stylesRules)
{
    $this->_stylesRules = $stylesRules;
}

Error saving temp file

hi!
yii2-excelexport use mikehaertl/php-tmpfile for temp files.

there is an issue about using sys_get_temp_dir on php.net

This function does not account for virtualhost-specific modifications to the temp path and/or open_basedir:

<Virtualhost>
php_admin_value open_basedir /home/user
php_admin_value upload_tmp_dir /home/user/tmp
php_admin_value session.save_path /home/user/tmp
</Virtualhost>

Within this config it still returns /tmp

so i can't save file...

...and @mikehaertl, you have any idea?

"Raw data" example crashes

Just copy-pasted "Raw data" example from README.md. Execution result was:

Invalid argument supplied for foreach()

  1. in sitedir/vendor/codemix/yii2-excelexport/src/ExcelSheet.php at line 250
  2. in sitedir/vendor/codemix/yii2-excelexport/src/ExcelFile.php at line 141 – codemix\excelexport\ExcelSheet::render()
  3. in sitedir/vendor/codemix/yii2-excelexport/src/ExcelFile.php at line 154 – codemix\excelexport\ExcelFile::createSheets()
  4. in sitedir/vendor/codemix/yii2-excelexport/src/ExcelFile.php at line 98 – codemix\excelexport\ExcelFile::createFile()
  5. in sitedir/controllers/TestController.php at line 137 – codemix\excelexport\ExcelFile::saveAs('filename' => ''test.xlsx'')

multiple sheets

$file = \Yii::createObject([
                    'class' => 'codemix\excelexport\ExcelFile',
                    'sheets' => [
                        'New-Registrations' => [
                            
                            'titles' => ['From','to','city'],  
                            'styles' => [
                            'A1:C1' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ],
                            'A4' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ] 
                                
                              ]
                            ],
                            'Re-Registrations' => [
                            
                            'titles' => ['From','to','city'],  
                            'styles' => [
                            'A1:C1' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ],
                            'A4' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ] 
                                
                              ]
                            ],
                            'Expirations-REC' => [
                            
                            'titles' => ['From','to','city'],  
                            'styles' => [
                            'A1:C1' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ],
                            'A4' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ] 
                                
                              ]
                            ],
                            'Expirations-ID' => [
                            
                            'titles' => ['From','to','city'],  
                            'styles' => [
                            'A1:C1' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ],
                            'A4' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ] 
                                
                              ]
                            ],
                            'Incidents' => [
                            
                            'titles' => ['From','to','city'],  
                            'styles' => [
                            'A1:C1' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ],
                            'A4' => [
                                'font' => [
                                     'bold' => true,
                                    'size'=>12
                                ]

                            ] 
                                
                              ]
                            ]
                        
                    ]
        ]);
  $file->getWorkbook()->getSheet(1);

i want to get second sheet but it is giving me error.
Your requested sheet index: 1 is out of bounds. The actual number of sheets is 1
please help me out as soon as possible

getSheet(1) returns "Your requested sheet index: 1 is out of bounds"

I am creating a 2 sheet Excel file which exports correctly. I can use getSheet(0) to setAutoSize() on columns on the first column, but not column 1.

The code to create the Excel file (as Raw data) is...

$sheets = array();

$sheet1 = array();
$data1 = array();
$sheet1['titles']=['Name'];
$data1[] = ['A long name'];
$sheet1['data']=$data1;

$sheets['First']=$sheet1;
$sheets['Second']=$sheet1;

$file = \Yii::createObject([
'class' => 'codemix\excelexport\ExcelFile',
'sheets' => $sheets
]);

And the code to set the column width is...

$file->getWorkbook()->getSheet(0)->getColumnDimension('A')->setAutoSize(true); // Works
$file->getWorkbook()->getSheet(1)->getColumnDimension('A')->setAutoSize(true); // Causes error.

Change default timezone

I am trying to display data in datetime format. But, PHPExcel convert it by default to UTC timezone. Is there any way to change the default timezone through your library?

It doesn't work

  public function actionPrintExcel(){

        $file = Yii::createObject([
            'class' => 'codemix\excelexport\ExcelFile',
            'sheets' => [
                'Licenses' => [
                    'class' => 'codemix\excelexport\ActiveExcelSheet',
                    'query' => License::find(),
                ]
            ]
        ]);
        $file->send('user.xlsx');
    }

Improvement: Separate sheet generation from create file

I encountered a problem when you need to have access to a particular sheet in multi sheet excel file. I had to combine rows and columns for different sheets. For this I had to use mergeCells method of object PHPExcel. And for each sheet call method mergeCells. Lets maybe separeta sheet generation from file create. So you can call $file->generateSheets(); and then foreach sheet $file->getWorkbook()->getSheet($currentSheet)->mergeCells($mergeArea);

/**
 * Create the Excel file and save it to the temp file
 */
protected function createFile()
{
    if (!$this->_created) {
        $this->generateSheets();
        $this->getWriter()->save((string)$this->getTmpFile());
        $this->_created = true;
    } else {
        $this->getWriter()->save((string)$this->getTmpFile());
    }
}

/**
 * Generate Excel Sheets
 * @throws \Exception
 */
public function generateSheets()
{
    $workbook = $this->getWorkbook();
    $i = 0;
    foreach ($this->sheets as $title => $config) {
        if (is_string($config)) {
            $config = ['class' => $config];
        } elseif (is_array($config)) {
            if (!isset($config['class'])) {
                $config['class'] = ExcelSheet::className();
            }
        } elseif (!is_object($config)) {
            throw new \Exception('Invalid sheet configuration');
        }
        $sheet = (0 === $i++) ? $workbook->getActiveSheet() : $workbook->createSheet();
        if (is_string($title)) {
            $sheet->setTitle($title);
        }
        Yii::createObject($config, [$sheet])->render();
    }
    $this->_created = true;
}

Implement pre calculated formulas.

In case when in cell insert formula it won't be calculated until user enter edit mode. On read mode, values in calculated cells will be 0.
To allow calculation on read mode, before save at writer should be used setPreCalculateFormulas() method.
By default preCalculateFormulas value should be false, i think.
For example if in configs object 'preCalculateFormulas' => true, than formulas will be calculated.

        public $preCalculateFormulas = false;
        $writer = new $class($workbook);
        if($this->preCalculateFormulas){
            $writer->setPreCalculateFormulas();
        }
        $writer->save((string) $this->getTmpFile());

Error In MSSQL Server

when export and use mssql server db this error show up :

SQLSTATE[IMSSP]: There are no more rows in the active result set. Since this result set is not scrollable, no more data may be retrieved.

How to set all cells in whole workbook to autosize?

I believe its possible to do this:

$file->getWorkbook()->getSheet(0)->getColumnDimension('A')->setWidth("35");
$file->getWorkbook()->getSheet(0)->getColumnDimension('B')->setAutoSize(true);

However is it possible to set all cells within a sheet to auto size?

in raw data example

Return thi issue ... I've copy and pasted the example, Invalid argument supplied for foreach()

Can this be used to get specific rows from a table?

I am confused where do I write this code??
In controller action or view?(when will this be triggered)
Can this be used to export specific data from database based on my query?
Can someone please clarify

php version

{
"name": "PHP Compile Error",
"message": "Array and string offset access syntax with curly braces is no longer supported",
"code": 64,
"type": "yii\base\ErrorException",
"file": "/home/netkostu/public_html/vendor/phpoffice/phpexcel/Classes/PHPExcel/Shared/String.php",
"line": 529,
"stack-trace": [
"#0 [internal function]: yii\base\ErrorHandler->handleFatalError()",
"#1 {main}"
]
}

Data from different models

How i can insert data from different models? In previous issue i asked about custom attribute, now i need to insert value from another model.

Trying to access array offset on value of type int

Error in vendor/phpoffice/phpexcel/Classes/PHPExcel/Cell/DefaultValueBinder.php

public static function dataTypeForValue($pValue = null)
{
    // Match the value against a few data types
    if ($pValue === null) {
        return PHPExcel_Cell_DataType::TYPE_NULL;
    } elseif ($pValue === '') {
        return PHPExcel_Cell_DataType::TYPE_STRING;
    } elseif ($pValue instanceof PHPExcel_RichText) {
        return PHPExcel_Cell_DataType::TYPE_INLINE;
    } elseif ($pValue{0} === '=' && strlen($pValue) > 1) {
        return PHPExcel_Cell_DataType::TYPE_FORMULA;
    } elseif (is_bool($pValue)) {
        return PHPExcel_Cell_DataType::TYPE_BOOL;
    } elseif (is_float($pValue) || is_int($pValue)) {
        return PHPExcel_Cell_DataType::TYPE_NUMERIC;
    } elseif (preg_match('/^[\+\-]?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) {
        $tValue = ltrim($pValue, '+-');
        if (is_string($pValue) && $tValue{0} === '0' && strlen($tValue) > 1 && $tValue{1} !== '.') {
            return PHPExcel_Cell_DataType::TYPE_STRING;

Specifictly in:

    } elseif ($pValue{0} === '=' && strlen($pValue) > 1) {

I suppose this error is phpoffice package.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.