• Stars
    star
    102
  • Rank 335,584 (Top 7 %)
  • Language
    PHP
  • Created over 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A utility to quickly create Excel files from query results or raw 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' => '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');
            }
        ],
    ],
]);

More Repositories

1

fast.js

Faster user-land reimplementations for several common builtin native JavaScript functions.
JavaScript
3,412
star
2

ts-sql

A SQL database implemented purely in TypeScript type annotations.
TypeScript
3,181
star
3

babel-plugin-typecheck

Static and runtime type checking for JavaScript in the form of a Babel plugin.
JavaScript
886
star
4

deprank

Use PageRank to find the most important files in your codebase.
TypeScript
878
star
5

yii2-localeurls

Automatic locale/language management for URLs
PHP
412
star
6

babel-plugin-closure-elimination

A Babel plugin which eliminates closures from your JavaScript wherever possible.
JavaScript
369
star
7

babel-plugin-contracts

Design by Contract for JavaScript via a Babel plugin.
JavaScript
266
star
8

babel-plugin-macros

Hygienic, non-syntactic macros for JavaScript via a Babel plugin.
JavaScript
261
star
9

oriento

Former official node.js driver for OrientDB. Fast, lightweight, uses the binary protocol. Now deprecated.
JavaScript
196
star
10

htmling

Polymer / HTML5 templating syntax for node.js
JavaScript
177
star
11

yii2-dockerized

A template for docker based Yii 2 applications
PHP
169
star
12

gitignore-parser

A simple .gitignore parser for node.js
JavaScript
97
star
13

contractual

Unobtrusive, backwards compatible, syntactic sugar for Design by contract in JavaScript.
JavaScript
72
star
14

babel-plugin-trace

This is a Babel plugin which adds a straightforward, declarative syntax for adding debug logging to JavaScript applications.
JavaScript
63
star
15

yii2-configloader

Build configuration arrays from config files and env vars.
PHP
61
star
16

yii2-streamlog

A Yii 2 log target for streams in URL format
PHP
52
star
17

yii2-dockerbase

Yii 2 base image for dockerized yii2 projects
Shell
39
star
18

YiiElasticSearch

Elastic Search client for Yii
PHP
33
star
19

malloc

Simple malloc() & free() implementation for node.js, built on top of array buffers.
JavaScript
25
star
20

reign

A persistent, typed objects implementation for node.js and the browser.
JavaScript
23
star
21

binary-protocol

Easy, fast, writers and readers for implementing custom binary protocols in node.js.
JavaScript
20
star
22

oauth2yii

An OAuth2 client / server extension for the Yii framework
PHP
17
star
23

modeling

Fast and flexible data models for node.js and the browser.
JavaScript
15
star
24

restyii

A RESTful extension for Yii.
PHP
15
star
25

babel-plugin-hyperhtml

Babel plugin which compiles JSX into hyperHTML
JavaScript
12
star
26

yii2-excel-message

Translate messages via Excel files
PHP
12
star
27

backing

Provides a virtual address space for large segments of memory via JavaScript ArrayBuffers, and operations for allocating and freeing within the address space, optionally via a simple reference counting garbage collector.
JavaScript
11
star
28

validating

Quick and easy validators for node.js and the browser.
JavaScript
10
star
29

babel-plugin-conditional

Conditionally applies a set of babel plugins based on the result of an expression evaluated at runtime.
JavaScript
10
star
30

yii2-bs3activeform

A Bootstrap 3 enhanced ActiveForm for Yii 2
PHP
9
star
31

url-route

Web component providing URL routing
JavaScript
9
star
32

htmling-demo-app

HTMLing demo running on express
CSS
8
star
33

garbage-collector

A garbage collector for JavaScript built on top of typed arrays.
JavaScript
8
star
34

geonames-importer

Imports geonames data into elasticsearch
JavaScript
7
star
35

orientdb-protobufs

An experiment to see how the orientdb binary protocol could look if it used protocol buffers.
Java
6
star
36

handlebarsphp

Transpiles handlebars templates into native PHP templates
PHP
6
star
37

atomicbuffers

Atomic `readInt32()`, `writeInt32()`, `readUInt32()` and `writeUInt32()` for node.js buffers.
JavaScript
6
star
38

classing

Fluent classes for node.js and the browser.
JavaScript
6
star
39

dispatching

Tiny routing / dispatch library for node and the browser.
JavaScript
5
star
40

casting

Tiny type casting library for node.js and the browser.
JavaScript
5
star
41

php-orientdb

A fast PHP driver for the OrientDB binary protocol.
PHP
5
star
42

obligations

Tiny JavaScript library for preconditions and postconditions, intended for use with Contractual.
JavaScript
4
star
43

AccessRestrictable

A Yii ActiveRecordBehavior that automatically applies conditions for access restriction to every query.
PHP
2
star
44

component-testing-library

A library for testing component driven UIs
TypeScript
2
star
45

bootstrap-css

Twitter Bootstrap CSS / LESS packaged for component.js instead of bower
CSS
2
star
46

miming

Processing and formatting for various mime types.
JavaScript
2
star
47

bs3activeform

A lightweight utility to render Bootstrap 3 forms in Yii
PHP
2
star
48

handlebarsgen

An extendable static code generator for handlebars templates, targetting languages other than JavaScript, e.g. PHP
CoffeeScript
2
star
49

malloc-append

Simple append-only alloc() implementation on top of buffers and array buffers.
JavaScript
1
star
50

jsx-email-nextjs

Reproduce an error with renderToStaticMarkup() in Next.js
TypeScript
1
star
51

bootstrap-tooltip

Twitter Bootstrap Tooltip plugin packaged for component.js instead of bower
JavaScript
1
star
52

bencha

Mocha-esque UI for the excellent benchmarkjs benchmarking library
CoffeeScript
1
star
53

bootstrap-transition

Twitter Bootstrap Transition plugin packaged for component.js instead of bower
JavaScript
1
star
54

urlrouter

Tiny URL routing for the browser
CoffeeScript
1
star
55

bootstrap-affix

Twitter Bootstrap Affix plugin packaged for component.js instead of bower
JavaScript
1
star
56

bootstrap-scrollspy

Twitter Bootstrap Scrollspy plugin packaged for component.js instead of bower
JavaScript
1
star