Yii2 выгрузка в excel

Yii2 PHP Excel

  1. Property
  2. Installation
  3. Usage
  4. TODO

Latest Stable Version
Total Downloads
Latest Unstable Version
License

Exporting PHP to Excel or Importing Excel to PHP.
Excel Widget for generate Excel File or for load Excel File.

Property

string $mode is an export mode or import mode. valid value are ‘export’ and ‘import’

boolean $isMultipleSheet for set the export excel with multiple sheet.

array $properties for set property on the excel object.

array $models Model object or DataProvider object with much data.

array $columns to get the attributes from the model, this valid value only the exist attribute on the model. If this is not set, then all attribute of the model will be set as columns.

array $headers to set the header column on first line. Set this if want to custom header. If not set, the header will get attributes label of model attributes.

string|array $fileName is a name for file name to export or import. Multiple file name only use for import mode, not work if you use the export mode.

string $savePath is a directory to save the file or you can blank this to set the file as attachment.

string $format for excel to export. Valid value are ‘Excel5’, ‘Excel2007’, ‘Excel2003XML’, ’00Calc’, ‘Gnumeric’.

boolean $setFirstTitle to set the title column on the first line. The columns will have a header on the first line.

boolean $asAttachment to set the file excel to download mode.

boolean $setFirstRecordAsKeys to set the first record on excel file to a keys of array per line. If you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.

boolean $setIndexSheetByName to set the sheet index by sheet name or array result if the sheet not only one

string $getOnlySheet is a sheet name to getting the data. This is only get the sheet with same name.

array|Formatter $formatter the formatter used to format model attribute values into displayable texts. This can be either an instance of Formatter or an configuration array for creating the Formatter instance. If this property is not set, the «formatter» application component will be used.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist moonlandsoft/yii2-phpexcel "*"

or add

"moonlandsoft/yii2-phpexcel": "*"

to the require section of your composer.json file.

Usage

Exporting Data

Exporting data into an excel file.

<?php

// export data only one worksheet.

moonlandphpexcelExcel::widget([
	'models' => $allModels,
	'mode' => 'export', //default value as 'export'
	'columns' => ['column1','column2','column3'], //without header working, because the header will be get label from attribute label. 
	'header' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'], 
]);

moonlandphpexcelExcel::export([
	'models' => $allModels, 
	'columns' => ['column1','column2','column3'], //without header working, because the header will be get label from attribute label. 
	'header' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
]);

// export data with multiple worksheet.

moonlandphpexcelExcel::widget([
	'isMultipleSheet' => true, 
	'models' => [
		'sheet1' => $allModels1, 
		'sheet2' => $allModels2, 
		'sheet3' => $allModels3
	], 
	'mode' => 'export', //default value as 'export' 
	'columns' => [
		'sheet1' => ['column1','column2','column3'], 
		'sheet2' => ['column1','column2','column3'], 
		'sheet3' => ['column1','column2','column3']
	],
	//without header working, because the header will be get label from attribute label. 
	'header' => [
		'sheet1' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'], 
		'sheet2' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'], 
		'sheet3' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3']
	],
]);

moonlandphpexcelExcel::export([
	'isMultipleSheet' => true, 
	'models' => [
		'sheet1' => $allModels1, 
		'sheet2' => $allModels2, 
		'sheet3' => $allModels3
	], 'columns' => [
		'sheet1' => ['column1','column2','column3'], 
		'sheet2' => ['column1','column2','column3'], 
		'sheet3' => ['column1','column2','column3']
	], 
	//without header working, because the header will be get label from attribute label. 
	'header' => [
		'sheet1' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
		'sheet2' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
		'sheet3' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3']
	],
]);

New Feature for exporting data, you can use this if you familiar yii gridview.
That is same with gridview data column.
Columns in array mode valid params are ‘attribute’, ‘header’, ‘format’, ‘value’, and footer (TODO).
Columns in string mode valid layout are ‘attribute:format:header:footer(TODO)’.

<?php
  
moonlandphpexcelExcel::export([
   	'models' => Post::find()->all(),
      	'columns' => [
      		'author.name:text:Author Name',
      		[
      				'attribute' => 'content',
      				'header' => 'Content Post',
      				'format' => 'text',
      				'value' => function($model) {
      					return ExampleClass::removeText('example', $model->content);
      				},
      		],
      		'like_it:text:Reader like this content',
      		'created_at:datetime',
      		[
      				'attribute' => 'updated_at',
      				'format' => 'date',
      		],
      	],
      	'headers' => [
     		'created_at' => 'Date Created Content',
		],
]);
Importing Data

Import file excel and return into an array.

<?php

$data = moonlandphpexcelExcel::import($fileName, $config); // $config is an optional

$data = moonlandphpexcelExcel::widget([
		'mode' => 'import', 
		'fileName' => $fileName, 
		'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel. 
		'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric. 
		'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
	]);

$data = moonlandphpexcelExcel::import($fileName, [
		'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel. 
		'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric. 
		'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
	]);

// import data with multiple file.

$data = moonlandphpexcelExcel::widget([
	'mode' => 'import', 
	'fileName' => [
		'file1' => $fileName1, 
		'file2' => $fileName2, 
		'file3' => $fileName3,
	], 
		'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel. 
		'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric. 
		'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
	]);

$data = moonlandphpexcelExcel::import([
	'file1' => $fileName1, 
	'file2' => $fileName2, 
	'file3' => $fileName3,
	], [
		'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel. 
		'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric. 
		'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
	]);

Result example from the code on the top :


// only one sheet or specified sheet.
Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2));

// data with multiple worksheet
Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)), [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)));

// data with multiple file and specified sheet or only one worksheet
Array([file1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)), [file2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)));

// data with multiple file and multiple worksheet
Array([file1] => Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)), [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2))), [file2] => Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2)), [Sheet2] => Array([0] => Array([name] => Anam, [email] => moh.khoirul.anaam@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@moonlandsoft.com, [framework interest] => Yii2))));

TODO

  • Adding footer params for columns in exporting data.

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' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            '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 PhpOfficePhpSpreadsheetWriterXlsx
sheets An array of sheet configurations (see below). The keys are used as sheet names.
fileOptions Options to pass to the constructor of mikehaertltmpFile. 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 PhpOfficePhpSpreadsheetWriterBaseWrite instance
getWorkbook() Returns the PhpOfficePhpSpreadsheetSpreadsheet workbook instance
getTmpFile() Returns the mikehaertltmpFile 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 PhpOfficePhpSpreadsheetCellCell 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' => 'codemixexcelexportExcelFile',

    'writerClass' => 'PhpOfficePhpSpreadsheetWriterXls', // Override default of `PhpOfficePhpSpreadsheetWriterXlsx`

    'sheets' => [

        'Active Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            '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' => 'codemixexcelexportExcelFile',
    '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 PhpOfficePhpSpreadsheetSharedDate::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' => 'codemixexcelexportExcelFile',
    'sheets' => [

        'Users' => [
            'data' => new (yiidbQuery)
                ->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' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            '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(PhpOfficePhpSpreadsheetStyleColor::COLOR_RED);
$file->send();

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

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'callbacks' => [
                // $cell is a PhpOfficePhpSpreadsheetCell object
                'A' => function ($cell, $row, $column) {
                    $cell->getStyle()->applyFromArray([
                        'font' => [
                            'bold' => true,
                        ],
                        'alignment' => [
                            'horizontal' => PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_RIGHT,
                        ],
                        'borders' => [
                            'top' => [
                                'style' => PhpOfficePhpSpreadsheetStyleBorder::BORDER_THIN,
                            ],
                        ],
                        'fill' => [
                            'fillType' => PhpOfficePhpSpreadsheetStyleFill::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' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'startRow' => 3,
            'on beforeRender' => function ($event) {
                $sheet = $event->sender->getSheet();
                $sheet->setCellValue('A1', 'List of current users');
            }
        ],
    ],
]);
$title = 'Consumers Report';
$model = new Review();

$objPHPExcel = new PhpOfficePhpSpreadsheetSpreadsheet();
$sheet=0;

$objPHPExcel->setActiveSheetIndex($sheet);

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$objPHPExcel->getActiveSheet()->setTitle($title);

$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 1, $model->getAttributeLabel('name'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 1, $model->getAttributeLabel('mobile'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, 1, $model->getAttributeLabel('email'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, 1, $model->getAttributeLabel('email_verified'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, 1, $model->getAttributeLabel('status'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, 1, $model->getAttributeLabel('previously_ordered'));
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, 1, $model->getAttributeLabel('created_at'));

foreach ($data->getModels() as $dk => $dv){
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $dk+2, $dv->name);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $dk+2, $dv->mobile);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $dk+2, $dv->email);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $dk+2, $dv->email_verified?"Yes":"No");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, $dk+2, Consumer::$statuses[$dv->status]);
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $dk+2, $dv->getPreviouslyOrdered()?"Yes":"No");
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $dk+2, date(Yii::$app->params['dateFormat'].' '.Yii::$app->params['timeFormat'], $dv->created_at));
}

header('Content-Type: application/vnd.ms-excel');
$filename = $title.".xls";
header('Content-Disposition: attachment;filename='.$filename .' ');
header('Cache-Control: max-age=0');
$objWriter = PhpOfficePhpSpreadsheetIOFactory::createWriter($objPHPExcel, 'Xls');
$objWriter->save('php://output');
die();

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

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

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

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

Время на прочтение
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

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

A utility to quickly create Excel files from query results or raw data

  • dev-master

  • 2.8.2

  • 2.8.1

  • 2.8.0

  • 2.7.2

  • 2.7.1

  • 2.7.0

  • 2.6.0

  • 2.5.0

  • 2.4.0

  • 2.3.1

  • 2.3.0

  • 2.2.0

  • 2.1.0

  • 2.0.0

  • 1.0.1

  • 1.0.0

  • 1.0.0-alpha

This package is auto-updated.

Last update: 2023-03-18 15:50:37 UTC


README

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' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            '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 PhpOfficePhpSpreadsheetWriterXlsx
sheets An array of sheet configurations (see below). The keys are used as sheet names.
fileOptions Options to pass to the constructor of mikehaertltmpFile. 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 PhpOfficePhpSpreadsheetWriterBaseWrite instance
getWorkbook() Returns the PhpOfficePhpSpreadsheetSpreadsheet workbook instance
getTmpFile() Returns the mikehaertltmpFile 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 PhpOfficePhpSpreadsheetCellCell 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' => 'codemixexcelexportExcelFile',

    'writerClass' => 'PhpOfficePhpSpreadsheetWriterXls', // Override default of `PhpOfficePhpSpreadsheetWriterXlsx`

    'sheets' => [

        'Active Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            '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' => 'codemixexcelexportExcelFile',
    '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 PhpOfficePhpSpreadsheetSharedDate::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' => 'codemixexcelexportExcelFile',
    'sheets' => [

        'Users' => [
            'data' => new (yiidbQuery)
                ->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' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            '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(PhpOfficePhpSpreadsheetStyleColor::COLOR_RED);
$file->send();

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

<?php
$file = Yii::createObject([
    'class' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'callbacks' => [
                // $cell is a PhpOfficePhpSpreadsheetCell object
                'A' => function ($cell, $row, $column) {
                    $cell->getStyle()->applyFromArray([
                        'font' => [
                            'bold' => true,
                        ],
                        'alignment' => [
                            'horizontal' => PhpOfficePhpSpreadsheetStyleAlignment::HORIZONTAL_RIGHT,
                        ],
                        'borders' => [
                            'top' => [
                                'style' => PhpOfficePhpSpreadsheetStyleBorder::BORDER_THIN,
                            ],
                        ],
                        'fill' => [
                            'fillType' => PhpOfficePhpSpreadsheetStyleFill::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' => 'codemixexcelexportExcelFile',
    'sheets' => [
        'Users' => [
            'class' => 'codemixexcelexportActiveExcelSheet',
            'query' => User::find(),
            'startRow' => 3,
            'on beforeRender' => function ($event) {
                $sheet = $event->sender->getSheet();
                $sheet->setCellValue('A1', 'List of current users');
            }
        ],
    ],
]);

Yii2 PHP Excel

Latest Stable Version
Total Downloads
Latest Unstable Version
License

Exporting PHP to Excel or Importing Excel to PHP.
Excel Widget for generate Excel File or for load Excel File.

Property

string $mode is an export mode or import mode. valid value are ‘export’ and ‘import’

boolean $isMultipleSheet for set the export excel with multiple sheet.

array $properties for set property on the excel object.

array $models Model object or DataProvider object with much data.

array $columns to get the attributes from the model, this valid value only the exist attribute on the model. If this is not set, then all attribute of the model will be set as columns.

array $headers to set the header column on first line. Set this if want to custom header. If not set, the header will get attributes label of model attributes.

string|array $fileName is a name for file name to export or import. Multiple file name only use for import mode, not work if you use the export mode.

string $savePath is a directory to save the file or you can blank this to set the file as attachment.

string $format for excel to export. Valid value are ‘Excel5’, ‘Excel2007’, ‘Excel2003XML’, ’00Calc’, ‘Gnumeric’.

boolean $setFirstTitle to set the title column on the first line. The columns will have a header on the first line.

boolean $asAttachment to set the file excel to download mode.

boolean $setFirstRecordAsKeys to set the first record on excel file to a keys of array per line. If you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.

boolean $setIndexSheetByName to set the sheet index by sheet name or array result if the sheet not only one

string $getOnlySheet is a sheet name to getting the data. This is only get the sheet with same name.

array|Formatter $formatter the formatter used to format model attribute values into displayable texts. This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]] instance. If this property is not set, the «formatter» application component will be used.

boolean $autoSize define the column auto size.

integer $setStartColNum to set start column num, define 1.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiier/yii2-phpexcel "*"

or add

"yiier/yii2-phpexcel": "*"

to the require section of your composer.json file.

Usage

Exporting Data

Exporting data into an excel file.

<?php

// export data only one worksheet.

yiierphpexcelExcel::widget([
	'models' => $allModels,
	'mode' => 'export', //default value as 'export'
	'columns' => ['column1','column2','column3'], //without header working, because the header will be get label from attribute label. 
	'header' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'], 
]);

yiierphpexcelExcel::export([
	'models' => $allModels, 
	'columns' => ['column1','column2','column3'], //without header working, because the header will be get label from attribute label. 
	'header' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
]);

// export data with multiple worksheet.

yiierphpexcelExcel::widget([
	'isMultipleSheet' => true, 
	'models' => [
		'sheet1' => $allModels1, 
		'sheet2' => $allModels2, 
		'sheet3' => $allModels3
	], 
	'mode' => 'export', //default value as 'export' 
	'columns' => [
		'sheet1' => ['column1','column2','column3'], 
		'sheet2' => ['column1','column2','column3'], 
		'sheet3' => ['column1','column2','column3']
	],
	//without header working, because the header will be get label from attribute label. 
	'header' => [
		'sheet1' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'], 
		'sheet2' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'], 
		'sheet3' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3']
	],
]);

yiierphpexcelExcel::export([
	'isMultipleSheet' => true, 
	'models' => [
		'sheet1' => $allModels1, 
		'sheet2' => $allModels2, 
		'sheet3' => $allModels3
	], 'columns' => [
		'sheet1' => ['column1','column2','column3'], 
		'sheet2' => ['column1','column2','column3'], 
		'sheet3' => ['column1','column2','column3']
	], 
	//without header working, because the header will be get label from attribute label. 
	'header' => [
		'sheet1' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
		'sheet2' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3'],
		'sheet3' => ['column1' => 'Header Column 1','column2' => 'Header Column 2', 'column3' => 'Header Column 3']
	],
]);

New Feature for exporting data, you can use this if you familiar yii gridview.
That is same with gridview data column.
Columns in array mode valid params are ‘attribute’, ‘header’, ‘format’, ‘value’, and footer (TODO).
Columns in string mode valid layout are ‘attribute:format:header:footer(TODO)’.

<?php
  
yiierphpexcelExcel::export([
   	'models' => Post::find()->all(),
      	'columns' => [
      		'author.name:text:Author Name',
      		[
      				'attribute' => 'content',
      				'header' => 'Content Post',
      				'format' => 'text',
      				'value' => function($model) {
      					return ExampleClass::removeText('example', $model->content);
      				},
      		],
      		'like_it:text:Reader like this content',
      		'created_at:datetime',
      		[
      				'attribute' => 'updated_at',
      				'format' => 'date',
      		],
      	],
      	'headers' => [
     		'created_at' => 'Date Created Content',
		],
]);
	  

Importing Data

Import file excel and return into an array.

<?php

$data = yiierphpexcelExcel::import($fileName, $config); // $config is an optional

$data = yiierphpexcelExcel::widget([
		'mode' => 'import', 
		'fileName' => $fileName, 
		'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel. 
		'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric. 
		'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
	]);

$data = yiierphpexcelExcel::import($fileName, [
		'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel. 
		'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric. 
		'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
		'setStartColNum' => 4, // set start Column num
	]);

// import data with multiple file.

$data = yiierphpexcelExcel::widget([
	'mode' => 'import', 
	'fileName' => [
		'file1' => $fileName1, 
		'file2' => $fileName2, 
		'file3' => $fileName3,
	], 
		'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel. 
		'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric. 
		'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
	]);

$data = yiierphpexcelExcel::import([
	'file1' => $fileName1, 
	'file2' => $fileName2, 
	'file3' => $fileName3,
	], [
		'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel. 
		'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric. 
		'getOnlySheet' => 'sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
	]);

Result example from the code on the top :


// only one sheet or specified sheet.
Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2));

// data with multiple worksheet
Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2)), [Sheet2] => Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2)));

// data with multiple file and specified sheet or only one worksheet
Array([file1] => Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2)), [file2] => Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2)));

// data with multiple file and multiple worksheet
Array([file1] => Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2)), [Sheet2] => Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2))), [file2] => Array([Sheet1] => Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2)), [Sheet2] => Array([0] => Array([name] => Anam, [email] => caizhenghai@gmail.com, [framework interest] => Yii2), [1] => Array([name] => Example, [email] => example@yiier.com, [framework interest] => Yii2))));

TODO

  • Adding footer params for columns in exporting data.

Credits

moonlandsoft/yii2-phpexcel

yii2tech / spreadsheet
Goto Github
PK

View Code? Open in Web Editor
NEW

81.0
6.0
20.0
59 KB

Yii2 extension for export to Excel

License: Other

PHP 100.00%
spreadsheet
yii2
extension
export
excel
libreoffice
xls
xlsx

spreadsheet’s People

Contributors

klimov-paul avatar

spreadsheet’s Issues

Permission denied with Xlsx writer

I get an error message when using Spreadsheet::send and Xlsx writer saying:

unlink(…AppDataLocalTempphp3945.tmp): Permission denied

$tmpResource needs to be closed before $writer->save($tmpFileName)

// ...
$tmpResourceMetaData = stream_get_meta_data($tmpResource);
$tmpFileName = $tmpResourceMetaData['uri'];

$tmpFileStatistics = fstat($tmpResource);
if ($tmpFileStatistics['size'] > 0) {
    return Yii::$app->getResponse()->sendStreamAsFile($tmpResource, $attachmentName, $options);
}

fclose($tmpResource);
$writer = IOFactory::createWriter($this->getDocument(), $writerType);
$writer->save($tmpFileName);
unset($writer);
// ...

The code above is working for .xls or .xlsx, I didn’t try with other formats

How to set the column width?

Just do not need to send to the @PHPOffice/phpspreadsheet documentation.
I tried to embed setWidth, but I would understand where else.

Exported excel file corrupted

I tried to export excel as given example using following code

$exporter = new Spreadsheet([ 'dataProvider' => new ActiveDataProvider([ 'query' => Subject::find(), 'pagination' => [ 'pageSize' => 100, // export batch size ], ]), ]); return $exporter->send('items.xls');

Unfortunately it generates corrupted file. Please find the attachment.
export_excel

May I know where am I wrong? Do we need to add headers as well? Is there any proper documentation except README?

Thanks

rich text is not rendered correctly

How to set rich text in specific column?

Method `save()` changes file path to lowercase.

Consider updating to phpoffice/phpspreadsheet

Allowed memory size

I get error for 8000+ array items
Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)

Q A
This Package Version 1.0.2
Yii Framework Version 2.0.15
«phpoffice/phpspreadsheet» Version not found in composer
PHP version 7.2
Operating system ubuntu 18
$orders = [...] // Array of 8000+ items

// item example
// 0 => [
//    "id" => "146472", "created" => "2021-06-01 17:01:28", "site", => "1", "status" => "Отменён", 
//    "address_to_delivery" => "Кропивницкий - 1", "price" => "956", "restaurant"=> "0", "delivery_datetime" => "14:33", 
//    "first_name" => "Дмитрий", "phone" => "0662784754", "start_delivery" => "Не передано курьеру" , 
//   "complited_draw_order" => "2021-06-01 17:02:30", "items_num" => "0", "pizzeria" => "К1", "marketing" => "Нет",
//    "promo" => "", "timeDelivery" => "Да"]

var_dump($orders); // This work

$dataProvider = new ArrayDataProvider([
            'allModels' => $orders,
            'pagination' => [
                'pageSize' => 100,
            ],
        ]);

$exporter = new Spreadsheet([
            'dataProvider' => $dataProvider,
            'title' => 'Orders',
            'columns' => [...],
            'batchSize' => 200,]);

return $exporter->send('Заказы с ' . $date_from . ' по '.$date_to . '.xls');

If number of items 6000 this is work correctly
Screenshot (11)

Can I return a base64 instead of saving the file?

I’m using PHPSpreadsheet to generate an Excel file that I want to attach to a mail message, together with a bunch of PDF files(using Mpdf).

With Mpdf I can simply do: return base64_encode($mpdf->Output())

and attach it to the email with:

 $file = base64_decode($this->actiongetPdfFile($postData['billing_profile']));

$message->attachContent($file, ['fileName' => 'file.pdf', 'contentType' => 'data:application/pdf']);

Is there a way to do something similar with PHPSpreadsheet (without the need to save the file to disk before)?

I saw that suggestions saying that it was possible using $objWriter->save(‘php://output’);, but this did not work with this plugin.

I believe that there is no further documentation aside from what is already on the initial page, right?

Loop multiple tables in one sheet (with differet Heading)

Is there any way to loop multiple tables with same header but different category? How?

This may need 3-5 rows break for the next loop

for($i = 0; i < 4; i++ ) {
$exporter = new Spreadsheet([
    'dataProvider' => new ArrayDataProvider([
        'allModels' => [
            [
                'id' => 1,
                'name' => 'first',
            ],
            [
                'id' => 2,
                'name' => 'second',
            ],
        ],
    ]),
    'columns' => [
        [
            'class' => SerialColumn::class,
        ],
        [
            'attribute' => 'id',
        ],
        [
            'attribute' => 'name',
        ],
    ],
])->render();
//Neds some break rows here...
}

Spreadsheet::send not worked for Xlsx writer

Add possibility to configure PhpOfficePhpSpreadsheetWriter

What steps will reproduce the problem?

If export to Csv some text with non latin symbos i get charset errored text.

What is the expected result?

In csv i try to see readable data such as «Несколько слов на русском языке»

What do you get instead?

I see data in wrong charset as «Р°РєС‚РёРІРЅР°»

Additional info

Problem can be solwed with possibility to configure writer such as:

$writer = IOFactory::createWriter($this->getDocument(), $writerType);
if ($writerType=='Csv') {$writer->useBOM=true;}
$writer->save($filename);

OR

$writer = IOFactory::createWriter($this->getDocument(), $writerType);
if ($writerType=='Csv') {$writer->excelCompatibility=true;}
$writer->save($filename);

OR

add $this->writerConfig property to yii2techspreadsheetSpreadsheet and apply it to $writer

OR

create new method and use it to get $writer (so i can use extend yii2techspreadsheetSpreadsheet of it )

publick function createWriter($writerType){
      return IOFactory::createWriter($this->getDocument(), $writerType);
}

!!! Please, add possibility to configure writer!

Q A
This Package Version 1.0.4
Yii Framework Version 2.0.13
«phpoffice/phpspreadsheet» Version 1.8.2
PHP version 7.0
Operating system ubuntu 16

After installing «yii2tech/spreadsheet»: «^1.0» using composer not showing in the vendor folder

After installing «yii2tech/spreadsheet»: «^1.0» using composer not showing in the vendor folder
folder missing «use yii2techspreadsheetSpreadsheet»;

Here below the following message after install using composer

Using version ^1.0 for yii2tech/spreadsheet
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals

  • Installing markbaker/complex (1.4.7): Downloading (100%)
  • Installing psr/simple-cache (1.0.1): Downloading (100%)
  • Installing phpoffice/phpspreadsheet (1.5.0): Downloading (100%)
  • Installing yii2tech/spreadsheet (1.0.2): Downloading (100%)
    phpoffice/phpspreadsheet suggests installing mpdf/mpdf (Option for rendering PDF with PDF Writer)
    phpoffice/phpspreadsheet suggests installing dompdf/dompdf (Option for rendering PDF with PDF Writer)
    phpoffice/phpspreadsheet suggests installing tecnickcom/tcpdf (Option for rendering PDF with PDF Writer)
    phpoffice/phpspreadsheet suggests installing jpgraph/jpgraph (Option for rendering charts, or including charts with PDF or HTML Writers)
    Package phpoffice/phpexcel is abandoned, you should avoid using it. Use phpoffice/phpspreadsheet instead.

Problems in console

Hi, thank you for this extension.
I’m trying to save a xls file from console but I get this error:
PHP Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home/****/vendor/yii2tech/spreadsheet/src/Spreadsheet.php on line 222
The same code works perfectly if called from the browser.
Any Idea?
Tryed in a different server and it works, but also tryed a different extension in the same server and works perfecty. Also your csv exporter works in both servers

is there function for Read Template, Modify Template and Export edited Template

i have template excel, i want to replace some field or row with data from my table and generate edited templates.
thanks

How to specify a static column?

I want to export a static colum to excel.

I tried:

attributes' => [
    [
        'label' => "One",
        'value' => 1,
    ]
]

This results in a error Illegal offset type in isset or empty.

Exporting JSON columns

I haven’t been able to dig in too deep here but even though this library and yii2tech/csv-grid both seem to be almost identical in config and functionality, CsvGrid exports JSON columns without issue while this library just skips over them, with identical options (data provider, column config). What could be the issue here?

datetime formatter

What steps will reproduce the problem?

What is the expected result?

string empty »

What do you get instead?

1970-01-01 08:00:00

Additional info

Q A
This Package Version 1.?.?
Yii Framework Version 2.0.31
«phpoffice/phpspreadsheet» Version 1.?.?
PHP version 7.2
Operating system widnow
 ['attribute' => 'released_time', 'format' => 'datetime'],

if released_time type is null,export file will see 1970-01-01 08:00:00.but my yii config formatter nullDisplay is »; and when use gridview:widget will render string ».

как задать ширину ячейки?

в коде нашел только выравнивание текста в ячейке

Is there any way to add image in data column

Question

What steps will reproduce the problem?

$model = [
    'data' => [
        '0.0.0' => [
            'reference_number' => 'DMG/00015/2022'
            'customer' => 'PT. Rapala Indonesia'
            'damage' => 'TEAR IN'
            'description' => 'Tingkat Oval 60% s/d 80 %'
            'files' => [
                0 => 'https://sgp1.digitaloceanspaces.com/files.online/goods/OVR3/.tmb/carbon_18_.png'
                1 => 'https://sgp1.digitaloceanspaces.com/files.online/goods/OVR3/.tmb/teahub.io-cbr250rr-wallpaper-3291320.jpeg'
            ]
        ]
        '0.0.1' => [
            'reference_number' => 'DMG/00015/2022'
            'customer' => 'PT. Rapala Indonesia'
            'damage' => 'TEAR OUT'
            'description' => 'Tingkat Oval 90% s/d 100 % R'
            'files' => [
                0 => 'https://sgp1.digitaloceanspaces.com/files.online/goods/OVR3/.tmb/WhatsApp%20Image%202021-12-22%20at%2012.22.19%20PM.jpeg'
                1 => 'https://sgp1.digitaloceanspaces.com/files.online/goods/OVR3/.tmb/carbon_13_.png'
                2 => 'https://sgp1.digitaloceanspaces.com/files.online/goods/OVR3/.tmb/carbon_14_.png'
                3 => 'https://sgp1.digitaloceanspaces.com/files.online/goods/OVR3/.tmb/Action%20Column.png'
            ]
        ]
    ]
]

What is the expected result?

Render those image files based on url given in one column

What do you get instead?

For now, I just can display it as raw text.

Additional info

This is the code for my implementation

    public function actionExportToExcel($id) {
        $model = DamageReport::find()->dataFormatExcel($id);
        $exporter = new Spreadsheet([
            'dataProvider' => new ArrayDataProvider([
                'allModels' =>$model['data']
            ]),
            'columns' => [
                'customer',
                'reference_number',
                'damage',
                'description',
                [
                    'attribute' => 'files',
                    'format' => 'raw',
                    'value' => function($model){
                        if($model['files']){
                            // for testing 
                            return Html::img($model['files'][0]) ;
                        }

                        return null;
                    }
                ],
            ],
        ]);
        return $exporter->send($model['reference_number'] .'.xls');
    }
Q A
This Package Version «yii2tech/spreadsheet»: «1.0.1»,
Yii Framework Version 2.0.43
«phpoffice/phpspreadsheet» Version unsure
PHP version 7.4.10
Operating system Docker Ubuntu 18.04

Howto specify attributes for related tables?

Great repo!

I want to change the label of an attribute of a related table. How can I specify attributes for related tables?

I tried:

'attributes' => [
    'myattrib1',  // works
    'othertable.myattrib2', // works
    [
        'attribute' => 'othertable.myattrib2', // doesn't work
        'label' => 'NewLabel',
    ]
]

how to set datatype

What steps will reproduce the problem?

What is the expected result?

What do you get instead?

Additional info

Q A
This Package Version 1.?.?
Yii Framework Version 2.0.?
«phpoffice/phpspreadsheet» Version 1.?.?
PHP version
Operating system

e.g. force set a number show as string, like

$cell->setCellValueExplicit(
    'A8',
    "01513789642",
    PhpOfficePhpSpreadsheetCellDataType::TYPE_STRING
);
$cell->setDataType(
    PhpOfficePhpSpreadsheetCellDataType::TYPE_STRING
);

send doesn’t work as expected

return Yii::$app->getResponse()->sendStreamAsFile($tmpResource, $attachmentName, $options);

This line uses yiiwebResponse::sendStreamAsFile, this method just prepares the file without send it to be downloaded as documented.
it would be nice to document what should be done if the user faces this use case.

screen shot 2019-02-03 at 10 40 24 am

Is there any way to add image as header, before data grid

Hi,

Is there any function to add image and title in data sheet before main data table?

Error when send a result file to the browser through download

wrapped Text option is not available

How can we wrap text for column

image

number overflow bug

Hello, I have a question about the format of spreadsheet. I use the package to export a excel, it may look like this:
$exporter = new Spreadsheet([ 'dataProvider' => $dataProvider, 'columns' => [ 'id', 'idCard', ] ]);
The idCard is an 18-digit number。but when I download the excel ,it show like this:
image

I just want it process the idCard as a string, this format is not I want. now the value is 411627200002085000. in fact, the value of idCard here is «411627200002084831». I think this bug is the number have overflowed。i think if I set the number format to text, it may work well. so I change code to this:
$exporter = new Spreadsheet([ 'dataProvider' => $dataProvider, 'columns' => [ 'id', [ 'attribute' => 'idCard', 'contentOptions' => [ 'numberFormat' => [ 'formatCode' => PhpOfficePhpSpreadsheetStyleNumberFormat::FORMAT_TEXT, ], ], ] ] ]);
the result change to this, it changed the format to text, but it still an Incorrect value.
image

I checked the code, and i think the reason is the number is too big. when we set value to cell ,it has already overflowed. and then ,I set the format to text, the value can’t change to the original value, so the text is wrong. the code is in «yii2tech/spreadsheet/src/Spreadsheet.php»,
public function renderCell($cell, $content, $style = []) { $sheet = $this->getDocument()->getActiveSheet(); $sheet->setCellValue($cell, $content); $this->applyCellStyle($cell, $style); return $this; }
when we set cellvalue ,the value has already overflowed, and then I can do noting to change the value to original value. I try to use setCellValueExplicit, and it work well.
Could you please change the function setCellValue to setCellValueExplicit, so I can set the value explicit?

String column specification produces format ‘text’ instead of ‘raw’

String column specification produces format ‘text’ instead of ‘raw’.
For example:

$exporter = new Spreadsheet([
    ///...,
    'columns' => [
        ['attribute' => 'name'], // format detected as 'raw'
        'description', // format detected as 'text'
    ],
]);
$exporter->save('/path/to/file.xls');

поправьте пожалуйста документацию (описание)

в Spreadsheet нет метода saveAs;
а так же последний пример, что за переменная $grid

Question : Set Style Text Format

What steps will reproduce the problem?

What is the expected result?

What do you get instead?

Additional info

Q A
This Package Version 1.?.?
Yii Framework Version 2.0.?
«phpoffice/phpspreadsheet» Version 1.?.?
PHP version
Operating system

Question:

Pleaser refer my setup, I am fiailed to formatting the column in generated excel.

image

The SerialColumn class does not work as I expected

What steps will reproduce the problem?

‘columns’ => [
[
‘class’ => SerialColumn::class,
]
]

What is the expected result?

row numbers in the result table

What do you get instead?

nothing

Additional info

it seems to me, in code some problem near by

  /**
   * Renders sheet table body batch.
   * This method will be invoked several times, one per each model batch.
   * @param array $models batch of models.
   * @param array $keys batch of model keys.
   * @param int $modelIndex model iteration index.
   */
protected function renderBody($models, $keys, &$modelIndex) {
    foreach ($models as $index => $model) {
      $key = isset($keys[$index]) ? $keys[$index] : $index;
      $columnIndex = 'A';
      foreach ($this->columns as $column) {

       /* the class of $column variable is the yiigridSerialColumn, but your code
        assumes that class of $column is your own Column and the renderDataCell
        fills the Column->grid property */

        /* @var $column Column */ 

        $column->renderDataCell($columnIndex . $this->rowIndex, $model, $key, $modelIndex);
        $columnIndex++;
      }
      $this->rowIndex++;
      $modelIndex++;
    }
  }
Q A
This Package Version 1.?.?
Yii Framework Version 2.0.?
«phpoffice/phpspreadsheet» Version 1.?.?
PHP version
Operating system

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.

  • Laravel photo
    Laravel

    A PHP framework for web artisans

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

  • Visualization

    Some thing interesting about visualization, use data art

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

  • Alibaba photo
    Alibaba

    Alibaba Open Source for everyone

  • D3 photo
    D3

    Data-Driven Documents codes.

  • Tencent photo
    Tencent

    China tencent open source team.

Spreadsheet Data Export extension for Yii2

This extension provides ability to export data to spreadsheet, e.g. Excel, LibreOffice etc.

For license information check the LICENSE-file.

Latest Stable Version
Total Downloads
Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yii2tech/spreadsheet

or add

"yii2tech/spreadsheet": "*"

to the require section of your composer.json.

Usage

This extension provides ability to export data to a spreadsheet, e.g. Excel, LibreOffice etc.
It is powered by phpoffice/phpspreadsheet library.
Export is performed via yii2techspreadsheetSpreadsheet instance, which provides interface similar to yiigridGridView widget.

Example:

<?php

use yii2techspreadsheetSpreadsheet;
use yiidataArrayDataProvider;

$exporter = new Spreadsheet([
    'dataProvider' => new ArrayDataProvider([
        'allModels' => [
            [
                'name' => 'some name',
                'price' => '9879',
            ],
            [
                'name' => 'name 2',
                'price' => '79',
            ],
        ],
    ]),
    'columns' => [
        [
            'attribute' => 'name',
            'contentOptions' => [
                'alignment' => [
                    'horizontal' => 'center',
                    'vertical' => 'center',
                ],
            ],
        ],
        [
            'attribute' => 'price',
        ],
    ],
]);
$exporter->save('/path/to/file.xls');

Please, refer to yii2techspreadsheetColumn class for the information about column properties and configuration specifications.

While running web application you can use yii2techspreadsheetSpreadsheet::send() method to send a result file to
the browser through download dialog:

<?php

use yii2techspreadsheetSpreadsheet;
use yiidataActiveDataProvider;
use yiiwebController;

class ItemController extends Controller
{
    public function actionExport()
    {
        $exporter = new Spreadsheet([
            'dataProvider' => new ActiveDataProvider([
                'query' => Item::find(),
            ]),
        ]);
        return $exporter->send('items.xls');
    }
}

Multiple sheet files

You can create an output file with multiple worksheets (tabs). For example: you may want to export data about
equipment used in the office, keeping monitors, mouses, keyboards and so on in separated listings but in the same file.
To do so you will need to manually call yii2techspreadsheetSpreadsheet::render() method with different configuration
before creating final file. For example:

<?php

use yii2techspreadsheetSpreadsheet;
use yiidataActiveDataProvider;
use appmodelsEquipment;

$exporter = (new Spreadsheet([
    'title' => 'Monitors',
    'dataProvider' => new ActiveDataProvider([
        'query' => Equipment::find()->andWhere(['group' => 'monitor']),
    ]),
    'columns' => [
        [
            'attribute' => 'name',
        ],
        [
            'attribute' => 'price',
        ],
    ],
]))->render(); // call `render()` to create a single worksheet

$exporter->configure([ // update spreadsheet configuration
    'title' => 'Mouses',
    'dataProvider' => new ActiveDataProvider([
        'query' => Equipment::find()->andWhere(['group' => 'mouse']),
    ]),
])->render(); // call `render()` to create a single worksheet

$exporter->configure([ // update spreadsheet configuration
    'title' => 'Keyboards',
    'dataProvider' => new ActiveDataProvider([
        'query' => Equipment::find()->andWhere(['group' => 'keyboard']),
    ]),
])->render(); // call `render()` to create a single worksheet

$exporter->save('/path/to/file.xls');

As the result you will get a single *.xls file with 3 worksheets (tabs): ‘Monitors’, ‘Mouses’ and ‘Keyboards’.

Using yii2techspreadsheetSpreadsheet::configure() you can reset any spreadsheet parameter, including columns.
Thus you are able to combine several entirely different sheets into a single file.

Large data processing

yii2techspreadsheetSpreadsheet allows exporting of the yiidataDataProviderInterface and yiidbQueryInterface instances.
Export is performed via batches, which allows processing of the large data without memory overflow.

In case of yiidataDataProviderInterface usage, data will be split to batches using pagination mechanism.
Thus you should setup pagination with page size in order to control batch size:

<?php

use yii2techspreadsheetSpreadsheet;
use yiidataActiveDataProvider;

$exporter = new Spreadsheet([
    'dataProvider' => new ActiveDataProvider([
        'query' => Item::find(),
        'pagination' => [
            'pageSize' => 100, // export batch size
        ],
    ]),
]);
$exporter->save('/path/to/file.xls');

Note: if you disable pagination in your data provider — no batch processing will be performed.

In case of yiidbQueryInterface usage, Spreadsheet will attempt to use batch() method, if it is present in the query
class (for example in case yiidbQuery or yiidbActiveQuery usage). If batch() method is not available —
yiidataActiveDataProvider instance will be automatically created around given query.
You can control batch size via yii2techspreadsheetSpreadsheet::$batchSize:

<?php

use yii2techspreadsheetSpreadsheet;
use yiidataActiveDataProvider;

$exporter = new Spreadsheet([
    'query' => Item::find(),
    'batchSize' => 200, // export batch size
]);
$exporter->save('/path/to/file.xls');

Note: despite batch data processing reduces amount of resources needed for spreadsheet file generation,
your program may still easily end up with PHP memory limit error on large data. This happens because of
large complexity of the created document, which is stored in the memory during the entire process.
In case you need to export really large data set, consider doing so via simple CSV data format
using yii2tech/csv-grid extension.

You may union some columns in the sheet header into a groups. For example: you may have 2 different data columns:
‘Planned Revenue’ and ‘Actual Revenue’. In this case you may want to display them as a single column ‘Revenue’, split
into 2 sub columns: ‘Planned’ and ‘Actual’.
This can be achieved using yii2techspreadsheetSpreadsheet::$headerColumnUnions. Its each entry
should specify ‘offset’, which determines the amount of columns to be skipped, and ‘length’, which determines
the amount of columns to be united. Other options of the union are the same as for regular column.
For example:

<?php

use yii2techspreadsheetSpreadsheet;
use yiidataArrayDataProvider;

$exporter = new Spreadsheet([
    'dataProvider' => new ArrayDataProvider([
        'allModels' => [
            [
                'column1' => '1.1',
                'column2' => '1.2',
                'column3' => '1.3',
                'column4' => '1.4',
                'column5' => '1.5',
                'column6' => '1.6',
                'column7' => '1.7',
            ],
            [
                'column1' => '2.1',
                'column2' => '2.2',
                'column3' => '2.3',
                'column4' => '2.4',
                'column5' => '2.5',
                'column6' => '2.6',
                'column7' => '2.7',
            ],
        ],
    ]),
    'headerColumnUnions' => [
        [
            'header' => 'Skip 1 column and group 2 next',
            'offset' => 1,
            'length' => 2,
        ],
        [
            'header' => 'Skip 2 columns and group 2 next',
            'offset' => 2,
            'length' => 2,
        ],
    ],
]);
$exporter->save('/path/to/file.xls');

Note: only single level of header column unions is supported. You will need to deal with more complex
cases on your own.

Custom cell rendering

Before save() or send() method is invoked, you are able to edit generated spreadsheet, making some
final adjustments to it. Several methods exist to facilitate this process:

  • yii2techspreadsheetSpreadsheet::renderCell() — renders specified cell with given content and style.
  • yii2techspreadsheetSpreadsheet::applyCellStyle() — applies specified style to the cell.
  • yii2techspreadsheetSpreadsheet::mergeCells() — merges sell range into single one.

You may use these methods, after document has been composed via yii2techspreadsheetSpreadsheet::render(),
to override or add some content. For example:

<?php

use yii2techspreadsheetSpreadsheet;
use yii2techspreadsheetSerialColumn;
use yiidataArrayDataProvider;

$exporter = new Spreadsheet([
    'dataProvider' => new ArrayDataProvider([
        'allModels' => [
            [
                'id' => 1,
                'name' => 'first',
            ],
            [
                'id' => 2,
                'name' => 'second',
            ],
        ],
    ]),
    'columns' => [
        [
            'class' => SerialColumn::class,
        ],
        [
            'attribute' => 'id',
        ],
        [
            'attribute' => 'name',
        ],
    ],
])->render(); // render the document

// override serial column header :
$exporter->renderCell('A1', 'Overridden serial column header');

// add custom footer :
$exporter->renderCell('A4', 'Custom A4', [
    'font' => [
        'color' => [
            'rgb' => '#FF0000',
        ],
    ],
]);

// merge footer cells :
$exporter->mergeCells('A4:B4');

$exporter->save('/path/to/file.xls');

Tip: you can use yii2techspreadsheetSpreadsheet::$rowIndex to get number of the row, which is next
to the last rendered one.

Open Source Agenda is not affiliated with «Yii2tech Spreadsheet» Project. README Source: yii2tech/spreadsheet

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
А потом я открыл для себя этот форум, очень много полезного тут можно подчерпнуть.

Согласен)

Понравилась статья? Поделить с друзьями:
  • Yii2 gridview to excel
  • Yield of maturity excel
  • Xml шаблон для excel
  • Xml что бы читал excel
  • Xml формат для excel