Commit 2d25db7d by mushishixian

excel包

parent 03d523c2
Showing with 4891 additions and 2 deletions
......@@ -10,7 +10,8 @@
"ext-json": "*",
"ext-curl": "*",
"predis/predis": "^1.1",
"vladimir-yuldashev/laravel-queue-rabbitmq": "5.2"
"vladimir-yuldashev/laravel-queue-rabbitmq": "5.2",
"maatwebsite/excel": "2.1.0"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
......
......@@ -155,6 +155,7 @@ return [
App\Providers\AuthServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
Maatwebsite\Excel\ExcelServiceProvider::class,
],
......
......@@ -60,7 +60,7 @@ class ClassLoader
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
......
......@@ -8,6 +8,8 @@ $baseDir = dirname($vendorDir);
return array(
'VladimirYuldashev\\LaravelQueueRabbitMQ' => array($vendorDir . '/vladimir-yuldashev/laravel-queue-rabbitmq/src'),
'UpdateHelper\\' => array($vendorDir . '/kylekatarnls/update-helper/src'),
'PHPExcel' => array($vendorDir . '/phpoffice/phpexcel/Classes'),
'Mockery' => array($vendorDir . '/mockery/mockery/library'),
'Maatwebsite\\Excel\\' => array($vendorDir . '/maatwebsite/excel/src'),
'JakubOnderka\\PhpConsoleHighlighter' => array($vendorDir . '/jakub-onderka/php-console-highlighter/src'),
);
......@@ -9,6 +9,7 @@ return array(
'phpDocumentor\\Reflection\\' => array($vendorDir . '/phpdocumentor/reflection-common/src', $vendorDir . '/phpdocumentor/reflection-docblock/src', $vendorDir . '/phpdocumentor/type-resolver/src'),
'XdgBaseDir\\' => array($vendorDir . '/dnoegel/php-xdg-base-dir/src'),
'Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'),
'TijsVerkoyen\\CssToInlineStyles\\' => array($vendorDir . '/tijsverkoyen/css-to-inline-styles/src'),
'Symfony\\Polyfill\\Util\\' => array($vendorDir . '/symfony/polyfill-util'),
'Symfony\\Polyfill\\Php56\\' => array($vendorDir . '/symfony/polyfill-php56'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
......
......@@ -13,6 +13,9 @@ class ComposerAutoloaderInit2a46e5674e69fd121680370ab820bf2e
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
......
......@@ -808,6 +808,82 @@
]
},
{
"name": "maatwebsite/excel",
"version": "v2.1.0",
"version_normalized": "2.1.0.0",
"source": {
"type": "git",
"url": "https://github.com/Maatwebsite/Laravel-Excel.git",
"reference": "e0a5afcf86aa4511b291584fae9f00c04e76e60c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Maatwebsite/Laravel-Excel/zipball/e0a5afcf86aa4511b291584fae9f00c04e76e60c",
"reference": "e0a5afcf86aa4511b291584fae9f00c04e76e60c",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"illuminate/cache": "5.0.*|5.1.*|5.2.*",
"illuminate/config": "5.0.*|5.1.*|5.2.*",
"illuminate/filesystem": "5.0.*|5.1.*|5.2.*",
"illuminate/support": "5.0.*|5.1.*|5.2.*",
"nesbot/carbon": "~1.0",
"php": ">=5.4",
"phpoffice/phpexcel": "1.8.*",
"tijsverkoyen/css-to-inline-styles": "~1.5"
},
"require-dev": {
"mockery/mockery": "~0.9",
"orchestra/testbench": "3.1.*",
"phpseclib/phpseclib": "~1.0",
"phpunit/phpunit": "~4.0"
},
"suggest": {
"illuminate/http": "5.0.*|5.1.*|5.2.*",
"illuminate/queue": "5.0.*|5.1.*|5.2.*",
"illuminate/routing": "5.0.*|5.1.*|5.2.*",
"illuminate/view": "5.0.*|5.1.*|5.2.*"
},
"time": "2015-12-10T18:31:14+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"classmap": [
"src/Maatwebsite/Excel",
"tests/TestCase.php"
],
"psr-0": {
"Maatwebsite\\Excel\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL"
],
"authors": [
{
"name": "Maatwebsite.nl",
"email": "patrick@maatwebsite.nl"
}
],
"description": "An eloquent way of importing and exporting Excel and CSV in Laravel 4 with the power of PHPExcel",
"keywords": [
"PHPExcel",
"batch",
"csv",
"excel",
"export",
"import",
"laravel"
]
},
{
"name": "mockery/mockery",
"version": "0.9.11",
"version_normalized": "0.9.11.0",
......@@ -1457,6 +1533,77 @@
"description": "A PSR-5 based resolver of Class names, Types and Structural Element Names"
},
{
"name": "phpoffice/phpexcel",
"version": "1.8.2",
"version_normalized": "1.8.2.0",
"source": {
"type": "git",
"url": "https://github.com/PHPOffice/PHPExcel.git",
"reference": "1441011fb7ecdd8cc689878f54f8b58a6805f870"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPOffice/PHPExcel/zipball/1441011fb7ecdd8cc689878f54f8b58a6805f870",
"reference": "1441011fb7ecdd8cc689878f54f8b58a6805f870",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"ext-mbstring": "*",
"ext-xml": "*",
"ext-xmlwriter": "*",
"php": "^5.2|^7.0"
},
"require-dev": {
"squizlabs/php_codesniffer": "2.*"
},
"time": "2018-11-22T23:07:24+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"PHPExcel": "Classes/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-2.1"
],
"authors": [
{
"name": "Maarten Balliauw",
"homepage": "http://blog.maartenballiauw.be"
},
{
"name": "Erik Tilt"
},
{
"name": "Franck Lefevre",
"homepage": "http://rootslabs.net"
},
{
"name": "Mark Baker",
"homepage": "http://markbakeruk.net"
}
],
"description": "PHPExcel - OpenXML - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine",
"homepage": "https://github.com/PHPOffice/PHPExcel",
"keywords": [
"OpenXML",
"excel",
"php",
"spreadsheet",
"xls",
"xlsx"
],
"abandoned": "phpoffice/phpspreadsheet"
},
{
"name": "phpspec/prophecy",
"version": "v1.10.3",
"version_normalized": "1.10.3.0",
......@@ -3791,6 +3938,61 @@
"homepage": "https://symfony.com"
},
{
"name": "tijsverkoyen/css-to-inline-styles",
"version": "1.5.5",
"version_normalized": "1.5.5.0",
"source": {
"type": "git",
"url": "https://github.com/tijsverkoyen/CssToInlineStyles.git",
"reference": "9753fc340726e327e4d48b7c0604f85475ae0bc3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tijsverkoyen/CssToInlineStyles/zipball/9753fc340726e327e4d48b7c0604f85475ae0bc3",
"reference": "9753fc340726e327e4d48b7c0604f85475ae0bc3",
"shasum": "",
"mirrors": [
{
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
"preferred": true
}
]
},
"require": {
"php": ">=5.3.0",
"symfony/css-selector": "~2.1|~3.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"time": "2015-12-08T16:14:14+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.5.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"TijsVerkoyen\\CssToInlineStyles\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD"
],
"authors": [
{
"name": "Tijs Verkoyen",
"email": "css_to_inline_styles@verkoyen.eu",
"role": "Developer"
}
],
"description": "CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.",
"homepage": "https://github.com/tijsverkoyen/CssToInlineStyles"
},
{
"name": "vladimir-yuldashev/laravel-queue-rabbitmq",
"version": "5.2",
"version_normalized": "5.2.0.0",
......
/vendor
composer.phar
composer.lock
.DS_Store
language: php
php:
- 5.4
- 5.5
- 5.6
before_script:
- travis_retry composer self-update
- travis_retry composer install --prefer-source --no-interaction
script: phpunit
matrix:
allow_failures:
- php: hhvm
fast_finish: true
\ No newline at end of file
## Laravel Excel v2.0.0 for Laravel 5
Looking for Laravel Excel for Laravel 4? Visit the [`1.3` branch](https://github.com/Maatwebsite/Laravel-Excel/tree/1.3)
[<img src="http://www.maatwebsite.nl/img/excel_banner.jpg"/>](http://www.maatwebsite.nl/laravel-excel/docs)
[<img src="https://cloud.githubusercontent.com/assets/7728097/6332170/1b495af2-bb84-11e4-9a93-34a9abc01840.jpg"/>](http://www.maatwebsite.nl/vacature-php-programmeur-maastricht)
Laravel Excel brings the power of PHPOffice's PHPExcel to Laravel 5 with a touch of the Laravel Magic. It includes features like: importing Excel and CSV to collections, exporting models, array's and views to Excel, importing batches of files and importing a file by a config file.
- Import into Laravel **Collections**
- Export **Blade views** to Excel and CSV with optional CSS styling
- **Batch** imports
- A lot of optional **config settings**
- Easy **cell caching**
- Chunked importer
- ExcelFile method injections
- Editing existing Excel files
- **Advanced import** by config files
- and many more...
---
```php
Excel::create('Laravel Excel', function($excel) {
$excel->sheet('Excel sheet', function($sheet) {
$sheet->setOrientation('landscape');
});
})->export('xls');
```
---
[![Build Status](https://travis-ci.org/Maatwebsite/Laravel-Excel.svg?branch=master)](https://travis-ci.org/Maatwebsite/Laravel-Excel)
[![Latest Stable Version](https://poser.pugx.org/maatwebsite/excel/v/stable.png)](https://packagist.org/packages/maatwebsite/excel) [![Total Downloads](https://poser.pugx.org/maatwebsite/excel/downloads.png)](https://packagist.org/packages/maatwebsite/excel) [![License](https://poser.pugx.org/maatwebsite/excel/license.png)](https://packagist.org/packages/maatwebsite/excel)
[![Monthly Downloads](https://poser.pugx.org/maatwebsite/excel/d/monthly.png)](https://packagist.org/packages/maatwebsite/excel)
[![Daily Downloads](https://poser.pugx.org/maatwebsite/excel/d/daily.png)](https://packagist.org/packages/maatwebsite/excel)
[![Help the project](http://www.pledgie.com/campaigns/30385.png?skin_name=chrome)](http://pledgie.com/campaigns/30385)
#Installation
Require this package in your `composer.json` and update composer. This will download the package and PHPExcel of PHPOffice.
```php
"maatwebsite/excel": "~2.0.0"
```
After updating composer, add the ServiceProvider to the providers array in `config/app.php`
```php
'Maatwebsite\Excel\ExcelServiceProvider',
```
You can use the facade for shorter code. Add this to your aliases:
```php
'Excel' => 'Maatwebsite\Excel\Facades\Excel',
```
The class is bound to the ioC as `excel`
```php
$excel = App::make('excel');
```
To publish the config settings in Laravel 5 use:
```php
php artisan vendor:publish
```
This will add an `excel.php` config file to your config folder.
# Documentation
The complete documentation can be found at: [http://www.maatwebsite.nl/laravel-excel/docs](http://www.maatwebsite.nl/laravel-excel/docs)
# Support
Support only through Github. Please don't mail us about issues, make a Github issue instead.
# Contributing
**ALL** bug fixes should be made to appropriate branch (e.g. `2.0` for 2.0.* bug fixes). Bug fixes should never be sent to the `master` branch.
More about contributing can be found at: [http://www.maatwebsite.nl/laravel-excel/docs/getting-started#contributing](http://www.maatwebsite.nl/laravel-excel/docs/getting-started#contributing)
# License
This package is licensed under LGPL. You are free to use it in personal and commercial projects. The code can be forked and modified, but the original copyright author should always be included!
{
"name": "maatwebsite/excel",
"description": "An eloquent way of importing and exporting Excel and CSV in Laravel 4 with the power of PHPExcel",
"license": "LGPL",
"keywords": [
"laravel",
"phpexcel",
"excel",
"csv",
"export",
"import",
"batch"
],
"authors": [
{
"name": "Maatwebsite.nl",
"email": "patrick@maatwebsite.nl"
}
],
"require": {
"php": ">=5.4",
"phpoffice/phpexcel": "1.8.*",
"illuminate/cache": "5.0.*|5.1.*|5.2.*",
"illuminate/config": "5.0.*|5.1.*|5.2.*",
"illuminate/filesystem": "5.0.*|5.1.*|5.2.*",
"illuminate/support": "5.0.*|5.1.*|5.2.*",
"nesbot/carbon": "~1.0",
"tijsverkoyen/css-to-inline-styles": "~1.5"
},
"require-dev": {
"phpseclib/phpseclib": "~1.0",
"phpunit/phpunit": "~4.0",
"mockery/mockery": "~0.9",
"orchestra/testbench": "3.1.*"
},
"suggest": {
"illuminate/http": "5.0.*|5.1.*|5.2.*",
"illuminate/routing": "5.0.*|5.1.*|5.2.*",
"illuminate/view": "5.0.*|5.1.*|5.2.*",
"illuminate/queue": "5.0.*|5.1.*|5.2.*"
},
"autoload": {
"classmap": [
"src/Maatwebsite/Excel",
"tests/TestCase.php"
],
"psr-0": {
"Maatwebsite\\Excel\\": "src/"
}
}
}
@include:Loading a view|load-view
@include:Passing variables|vars
@include:Styling sheets|styling
\ No newline at end of file
# @Blade to Excel
We can utilise the magic of Laravel's Blade engine to power our Excel export. Sharing a view, loading a view per sheet, creating a html table inside a view, basic CSS styling, ...
# Loading a view for a single sheet
We can load a view for every sheet we create with `->loadView()`.
Excel::create('New file', function($excel) {
$excel->sheet('New sheet', function($sheet) {
$sheet->loadView('folder.view');
});
});
# Using different views for different sheets
Excel::create('New file', function($excel) {
$excel->sheet('First sheet', function($sheet) {
$sheet->loadView('view_first');
});
$excel->sheet('Second sheet', function($sheet) {
$sheet->loadView('view_second');
});
});
# Sharing a view for all sheets
We can share a view for all sheets with `shareView()`.
Excel::shareView('folder.view')->create();
# Unsetting a view for a sheet
When we are using a shared view, but we don't want to use a view for the current sheet, we can use `->unsetView()`.
$sheet->unsetView();
\ No newline at end of file
# Styling sheets
### General styling
If you want to change the general styling of your sheet (not cell or range specific), you can use the `->setStyle()` method or any of the other setters which can be found inside the export documentation.
// Font family
$sheet->setFontFamily('Comic Sans MS');
// Set font with ->setStyle()`
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 12,
'bold' => true
)
));
### Styling with PHPExcel methods
It's possible to style the sheets and specific cells with help of PHPExcel methods. This package includes a lot of shortcuts (see export documentation), but also always the use of the native methods.
// Set background color for a specific cell
$sheet->getStyle('A1')->applyFromArray(array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'FF0000')
)
));
### Using HTML tags
Most of the HTML tags are supported.
<html>
<!-- Headings -->
<td><h1>Big title</h1></td>
<!-- Bold -->
<td><b>Bold cell</b></td>
<td><strong>Bold cell</strong></td>
<!-- Italic -->
<td><i>Italic cell</i></td>
<!-- Images -->
<td><img src="img.jpg" /></td>
</html>
> Inside the `view.php` config you can change how these tags will be interpreted by Excel by default.
### Using HTML attributes
Some of the basic styling can be done with HTML attributes.
<html>
<!-- Horizontal alignment -->
<td align="right">Big title</td>
<!-- Vertical alignment -->
<td valign="middle">Bold cell</td>
<!-- Rowspan -->
<td rowspan="3">Bold cell</td>
<!-- Colspan -->
<td colspan="6">Italic cell</td>
<!-- Width -->
<td width="100">Cell with width of 100</td>
<!-- Height -->
<td height="100">Cell with height of 100</td>
</html>
### Styling through inline-styles
It's possible to use inline styles inside your view files. Most of the general styles are supported.
<html>
<!-- Cell with black background -->
<td style="background-color: #000000;">Cell</td>
</html>
> Inside the reference guide you can find a list of supported styles.
### Styling through external CSS file
Styling can be done through an external CSS file.
External css file:
#cell {
background-color: #000000;
color: #ffffff;
}
.cell {
background-color: #000000;
color: #ffffff;
}
tr td {
background-color: #ffffff;
}
tr > td {
border-bottom: 1px solid #000000;
}
Table:
<html>
{{ HTML::style('css/table.css') }}
<!-- Cell styled with class -->
<td class="cell">Cell</td>
<!-- Cell styled with ID -->
<td id="cell">Cell</td>
</html>
> Inside the reference guide you can find a list of supported styles.
> It's advised to include `<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />` into the view to fix problems with UTF-8 encoding.
\ No newline at end of file
# Passing variables to the view
### As parameter
We can pass variables to the view by using the second parameter inside the `loadView()` method.
$sheet->loadView('view', array('key' => 'value'));
### With with()
Alternatively you can use the `with()` method which works the same as with Laravel views.
// Using normal with()
$sheet->loadView('view')
->with('key', 'value');
// using dynamic with()
$sheet->loadView('view')
->withKey('value');
\ No newline at end of file
PHPExcel_Style_Border::BORDER_NONE = 'none'
PHPExcel_Style_Border::BORDER_DASHDOT = 'dashDot'
PHPExcel_Style_Border::BORDER_DASHDOTDOT = 'dashDotDot'
PHPExcel_Style_Border::BORDER_DASHED = 'dashed'
PHPExcel_Style_Border::BORDER_DOTTED = 'dotted'
PHPExcel_Style_Border::BORDER_DOUBLE = 'double'
PHPExcel_Style_Border::BORDER_HAIR = 'hair'
PHPExcel_Style_Border::BORDER_MEDIUM = 'medium'
PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT = 'mediumDashDot'
PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot'
PHPExcel_Style_Border::BORDER_MEDIUMDASHED = 'mediumDashed'
PHPExcel_Style_Border::BORDER_SLANTDASHDOT = 'slantDashDot'
PHPExcel_Style_Border::BORDER_THICK = 'thick'
PHPExcel_Style_Border::BORDER_THIN = 'thin'
\ No newline at end of file
@include:Version 1|version-1
@include:Version 2|version-2
# Version 1
### 1.3.5
- PHPExcel 1.8.1 compatibility
- Clean-up ServiceProvider
- Fix short array syntax for PHP5.3
### 1.3.4
- Fix usage of sheet callback when modifying an existing file
- Modifying existing files improvements (support style overriding)
- Add text-indent support to HtmlReader
- Add simple sheet password protection
- Add support for exporting multiple pdf pages
- Add inline cell formatting to blade
### 1.3.3
- Fix issue with different start row in chunk filter
### 1.3.2
- Custom value binders
- Html reader update
### 1.3.1
- Fix short array syntax
### 1.3.0
- Additional headers with export()
- Float, integer, string, timestamps problems
- Cell content ending by zeros
- Images in html
- Font family bug
- Setting row number of row with headings
### 1.2.3
- PDF writer
- Include charts config
- Chunk filter with selected sheet
- Compatibility fix with new PHPExcel release
- setDateColumns fix
- Optional dependencies to require-dev
- Several bugfixes
### 1.2.2
- Chunk filter fixes
- Isset() CellCollection fixes
- PHP 5.3 support
- Missing border styles
- Add CSV settings (delimiter, enclosure, lineEnding) to ExcelFile objects
### 1.2.1
- Fix with() method parameters
### 1.2.0
- Filters
- Chunk filter (with chunked importer)
- ExcelFile (method) injections
- NewExcelFile (method) injections
- Edit existing worksheets
- Converting existing worksheet
- Laravel 4.* + 5.0 support
### 1.1.9
- PHP 5.3 fixes
### 1.1.8
- PHP 5.3 support
- fromArray bugfix
### 1.1.7
- Fix heading generation for export with `->fromArray()`
- Bugfix for non-Unix kernels
- Enhanced CSS parser (thanks to `tijsverkoyen/CssToInlineStyles`)
- Support for nested CSS styles
- Support for multiple css attributes per class
- Support for internal and external CSS files
- Support for inline style blocks (`<style>`)
### 1.1.6
- Provides.json fix
- DocBlock fixes
- Define Illuminate dependencies inside composer.json
- Better HTML rowspan handling views
- use new CellCollection() instead of ::make, to support upcoming Laravel version
- Workaround for long integers
- Add support to `wrap-text` in views
- Fix empty dates parsing
- Support local stylesheets in view parsing
- Push tr classes to td-children in views
- Support for dynamically appending rows to an empty (new) sheet
- Fix separator typo in config
### 1.1.5
- Select sheets by index with `Excel::selectSheetsByIndex(0,1)->load(...)`
- Separator typo fix
- Added `->setFileName()` method
- Use `->setTitle()` only for workbook title not for setting the filename anymore
- Made `setAutoSize()` chainable for other sheet methods
- Export config setting to disable pre calculation of formulas during export
- Export config setting to set the autosizing method (approx|exact)
- Auto sizing export from view fix
### 1.1.4
- Fix for importing 0 as null
- New unit tests
### 1.1.3
- Cell writer `->setBorder()` fix
### 1.1.2
- Fix for multiple imports on one pageload
- Multiple new import heading conversions (`Config: excel::import.heading: true|false|slugged|ascii|numeric|hashed|trans|original`)
### 1.1.1
- Retrieve workbook and sheet title during import (`->getTitle()`)
### 1.1.0
- `Limit()`, `skip()` and `take()` support for fetching results
- Set default page margins
- Export Eloquent models directly (`fromModel()`)
- Auto generate the first row (table heading) from the array keys
- Manipulate cells and cell ranges inside a closure
- Set cell backgrounds/fonts/values, ...
- Create/append/prepend new row/rows
- Manipulate row cells (background, fonts, ...)
- Config value default alignment on merge cells
- DocBlock updates to support better use of IDE autocomplete features
- Parse width and height inside views
- Parse images in views
- Optional to ASCII conversion of imported header columns (array indices)
- Config values for default null comparision and start cells for exports
- Changed default CSV enclosure to `"`
- Support for Laravel package installer
### 1.0.9
- Blade to Excel export fix for PHP5.3
### 1.0.8
- File format identifier enhancements
### 1.0.7
- Set workbook properties fix
- Extra units tests
### 1.0.6
- BatchReader fix
### 1.0.5
- Date parsing fix
### 1.0.4
- Fix calling $this in anonymous function to set locale and cache
### 1.0.3
- Table headings to attribute names undefined offset fix
- Composer.json enhancements
- Documentation fixes
### 1.0.2
- Cell Collection fixes
- Default autosizing bugfixes
- ->load() accepts input encoding parameter
- Documentation fixes
### 1.0.1
- Column width and row height bugfix
- Typo fixes
### 1.0.0
- New documentation
- More logical file structure (dividing into files, separating the different functionality (import / export)
- More optional config settings
- CSV Delimiter fixes
- CSV Encoding
- Import into collections (to support utilisation of ->first(), etc.)
- Better column selecting and result limiting
- Batch upload
- Import dates as Carbon objects by default
- Advanced file import through config coordinates
- Select sheets to import
- Create closure (Excel::create('file', function($excel) { } ))
- More logical syntax for creating new files, syntaxes of creating by array and creating with view should be as identical as possible
- Rewrite of sheet building for views
- Using closures to build sheets for normal sheet creation
- Better support for calling native PHPExcel methods
- Better use of setters
- Config setting to set default store behavior
- Column/row width
- Share views over all sheets + easy views switching per sheet
- External stylesheet with classes/ids parsing for views
- Colspan fix
- Th default styling
- Caching / Cell caching
# Version 2
### 2.0.4
- PHPExcel 1.8.1 compatibility
- Clean-up ServiceProvider
### 2.0.3
- Fix usage of sheet callback when modifying an existing file
- Modifying existing files improvements (support style overriding)
- Add text-indent support to HtmlReader
- Add simple sheet password protection
- Add support for exporting multiple pdf pages
- Add inline cell formatting to blade
### 2.0.2
- Fix issue with different start row in chunk filter
### 2.0.1
- Custom value binders
- Html reader update
### 2.0.0
- Laravel 5 release
@include:Creating a new file|simple
@include:Exporting|export
@include:NewExcelFile injections|injection
@include:Store to server|store
@include:Creating Sheets|sheets
@include:Creatings Sheets From array|array
@include:Row manipulation|rows
@include:Cell manipulation|cells
@include:Sheet styling|sheet-styling
@include:Freeze rows|freeze
@include:Auto filter|autofilter
@include:Cell sizing|sizing
@include:Auto size|autosize
@include:Column merging|merge
@include:Column formatting|format
@include:PHPExcel methods|call
\ No newline at end of file
# Creating a sheet from an array
## Array
To create a new file from an array use `->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration)` inside the sheet closure.
Excel::create('Filename', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
$sheet->fromArray(array(
array('data1', 'data2'),
array('data3', 'data4')
));
});
})->export('xls');
Alternatively you can use `->with()`.
$sheet->with(array(
array('data1', 'data2'),
array('data3', 'data4')
));
If you want to pass variables inside the closure, use `use($data)`
$data = array(
array('data1', 'data2'),
array('data3', 'data4')
);
Excel::create('Filename', function($excel) use($data) {
$excel->sheet('Sheetname', function($sheet) use($data) {
$sheet->fromArray($data);
});
})->export('xls');
### Null comparision
By default 0 is shown as an empty cell. If you want to change this behaviour, you can pass true as 4th parameter:
// Will show 0 as 0
$sheet->fromArray($data, null, 'A1', true);
>> To change the default behaviour, you can use `excel::export.sheets.strictNullComparison` config setting.
## Eloquent model
It's also possible to pass an Eloquent model and export it by using `->fromModel($model)`. The method accepts the same parameters as fromArray
## Auto heading generation
By default the export will use the keys of your array (or model attribute names) as first row (header column). To change this behaviour you can edit the default config setting (`excel::export.generate_heading_by_indices`) or pass `false` as 5th parameter:
// Won't auto generate heading columns
$sheet->fromArray($data, null, 'A1', false, false);
\ No newline at end of file
# Auto filter
To enable the auto filter use `->setAutoFilter($range = false)`.
// Auto filter for entire sheet
$sheet->setAutoFilter();
// Set auto filter for a range
$sheet->setAutoFilter('A1:E10');
\ No newline at end of file
# Auto size
By default the exported file be automatically auto sized. To change this behaviour you can either change the config or use the setters:
// Set auto size for sheet
$sheet->setAutoSize(true);
// Disable auto size for sheet
$sheet->setAutoSize(false);
// Disable auto size for columns
$sheet->setAutoSize(array(
'A', 'C'
));
> The default config setting can be found in: `export.php`.
\ No newline at end of file
# Calling PHPExcel's native methods
It's possible to call all native PHPExcel methods on the `$excel` and `$sheet` objects.
### Calling Workbook methods
Example:
// Get default style for this workbook
$excel->getDefaultStyle();
### Calling worksheet methods
Example:
// Protect cells
$sheet->protectCells('A1', $password);
> Head over to PHPOffice to learn more about the native methods.
\ No newline at end of file
# Cell manipulation
$sheet->cell('A1', function($cell) {
// manipulate the cell
});
$sheet->cells('A1:A5', function($cells) {
// manipulate the range of cells
});
### Set background
To change the background of a range of cells we can use `->setBackground($color, $type, $colorType)`
// Set black background
$cells->setBackground('#000000');
### Change fonts
// Set with font color
$cells->setFontColor('#ffffff');
// Set font family
$cells->setFontFamily('Calibri');
// Set font size
$cells->setFontSize(16);
// Set font weight to bold
$cells->setFontWeight('bold');
// Set font
$cells->setFont(array(
'family' => 'Calibri',
'size' => '16',
'bold' => true
));
### Set borders
// Set all borders (top, right, bottom, left)
$cells->setBorder('solid', 'none', 'none', 'solid');
// Set borders with array
$cells->setBorder(array(
'borders' => array(
'top' => array(
'style' => 'solid'
),
)
));
### Set horizontal alignment
// Set alignment to center
$cells->setAlignment('center');
### Set vertical alignment
// Set vertical alignment to middle
$cells->setValignment('middle');
\ No newline at end of file
# Exporting
To download the created file, use `->export($ext)` or `->download($ext)`.
#### Export to Excel5 (xls)
Excel::create('Filename', function($excel) {
})->export('xls');
// or
->download('xls');
#### Export to Excel2007 (xlsx)
->export('xlsx');
// or
->download('xlsx');
#### Export to CSV
->export('csv');
// or
->download('csv');
> You can set the default enclosure and delimiter inside the config
#### Export to PDF
To export files to pdf, you will have to include `"dompdf/dompdf": "~0.6.1"`, `"mpdf/mpdf": "~5.7.3"` or `"tecnick.com/tcpdf": "~6.0.0"` in your `composer.json` and change the `export.pdf.driver` config setting accordingly.
->export('pdf');
\ No newline at end of file
# Column formatting
To tell Excel how it should interpret certain columns, you can use `->setColumnFormat($array)`.
// Format column as percentage
$sheet->setColumnFormat(array(
'C' => '0%'
));
// Format a range with e.g. leading zeros
$sheet->setColumnFormat(array(
'A2:K2' => '0000'
));
// Set multiple column formats
$sheet->setColumnFormat(array(
'B' => '0',
'D' => '0.00',
'F' => '@',
'F' => 'yyyy-mm-dd',
));
> Go to the reference guide to see a list of available formats.
# Freeze rows
If you want to freeze a cell, row or column, use:
// Freeze first row
$sheet->freezeFirstRow();
// Freeze the first column
$sheet->freezeFirstColumn();
// Freeze the first row and column
$sheet->freezeFirstRowAndColumn();
// Set freeze
$sheet->setFreeze('A2');
\ No newline at end of file
# NewExcelFile injections
Following the Laravel 5.0 philosophy with its new awesome FormRequest injections, we introduce you NewExcelFile injections.
## NewExcelFile class
This NewExcelFile is a wrapper for a new Excel file. Inside the `getFilename()` you can declare the wanted filename.
class UserListExport extends \Maatwebsite\Excel\Files\NewExcelFile {
public function getFilename()
{
return 'filename';
}
}
## Usage
You can inject these NewExcelFiles inside the __constructor or inside the method (when using Laravel 5.0), in e.g. the controller.
class ExampleController extends Controller {
public function exportUserList(UserListExport $export)
{
// work on the export
return $export->sheet('sheetName', function($sheet)
{
})->export('xls');
}
}
## Export Handlers
To decouple your Excel-export code completely from the controller, you can use the export handlers.
class ExampleController extends Controller {
public function exportUserList(UserListExport $export)
{
// Handle the export
$export->handleExport();
}
}
The `handleExport()` method will dynamically call a handler class which is your class name appended with `Handler`
class UserListExportHandler implements \Maatwebsite\Excel\Files\ExportHandler {
public function handle(UserListExport $export)
{
// work on the export
return $export->sheet('sheetName', function($sheet)
{
})->export('xls');
}
}
# Column merging
### Merging cells
To merge a range of cells, use `->mergeCells($range)`.
$sheet->mergeCells('A1:E1');
### Merging columns and rows
To merge columns and rows, use `->setMergeColumn($array)`.
$sheet->setMergeColumn(array(
'columns' => array('A','B','C','D'),
'rows' => array(
array(2,3),
array(5,11),
)
));
\ No newline at end of file
# Row manipulation
### Manipulate certain row
#### Change cell values
// Manipulate first row
$sheet->row(1, array(
'test1', 'test2'
));
// Manipulate 2nd row
$sheet->row(2, array(
'test3', 'test4'
));
#### Manipulate row cells
// Set black background
$sheet->row(1, function($row) {
// call cell manipulation methods
$row->setBackground('#000000');
});
### Append row
// Append row after row 2
$sheet->appendRow(2, array(
'appended', 'appended'
));
// Append row as very last
$sheet->appendRow(array(
'appended', 'appended'
));
### Prepend row
// Add before first row
$sheet->prependRow(1, array(
'prepended', 'prepended'
));
// Add as very first
$sheet->prependRow(array(
'prepended', 'prepended'
));
### Append multiple rows
// Append multiple rows
$sheet->rows(array(
array('test1', 'test2'),
array('test3', 'test4')
));
// Append multiple rows
$sheet->rows(array(
array('test5', 'test6'),
array('test7', 'test8')
));
\ No newline at end of file
# Sheet styling
### General styling
If you want to change the general styling of your sheet (not cell or range specific), you can use the `->setStyle()` method.
// Set font with ->setStyle()`
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 15,
'bold' => true
)
));
### Fonts
To change the font for the current sheet use `->setFont($array)`:
$sheet->setFont(array(
'family' => 'Calibri',
'size' => '15',
'bold' => true
));
#### Separate setters
// Font family
$sheet->setFontFamily('Comic Sans MS');
// Font size
$sheet->setFontSize(15);
// Font bold
$sheet->setFontBold(true);
### Borders
You can set borders for the sheet, by using:
// Sets all borders
$sheet->setAllBorders('thin');
// Set border for cells
$sheet->setBorder('A1', 'thin');
// Set border for range
$sheet->setBorder('A1:F10', 'thin');
> Go to the reference guide to see a list of available border styles
\ No newline at end of file
# Sheets
### Creating a sheet
To create a new sheet inside our newly created file, use `->sheet('Sheetname')`.
Excel::create('Filename', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
// Sheet manipulation
});
})->export('xls');
### Creating multiple sheets
You can set as many sheets as you like inside the file:
Excel::create('Filename', function($excel) {
// Our first sheet
$excel->sheet('First sheet', function($sheet) {
});
// Our second sheet
$excel->sheet('Second sheet', function($sheet) {
});
})->export('xls');
### Changing properties
There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See `app/config/packages/maatwebsite/excel/config.php`.
Excel::create('Filename', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
$sheet->setOrientation('landscape');
});
})->export('xls');
> Go to the reference guide to see a list of available properties.
### Default page margin
It's possible to set the default page margin inside the config file `excel::export.sheets`.
It accepts boolean, single value or array.
To manually set the page margin you can use: `->setPageMargin()`
// Set top, right, bottom, left
$sheet->setPageMargin(array(
0.25, 0.30, 0.25, 0.30
));
// Set all margins
$sheet->setPageMargin(0.25);
### Password protecting a sheet
A sheet can be password protected with `$sheet->protect()`:
// Default protect
$sheet->protect('password');
// Advanced protect
$sheet->protect('password', function(\PHPExcel_Worksheet_Protection $protection) {
$protection->setSort(true);
});
# Simple Excel Export
### Basics
A new file can be created using the `create` method with the filename as first parameter.
Excel::create('Filename');
To manipulate the creation of the file you can use the callback
Excel::create('Filename', function($excel) {
// Call writer methods here
});
### Changing properties
There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See `app/config/packages/maatwebsite/excel/config.php`.
Excel::create('Filename', function($excel) {
// Set the title
$excel->setTitle('Our new awesome title');
// Chain the setters
$excel->setCreator('Maatwebsite')
->setCompany('Maatwebsite');
// Call them separately
$excel->setDescription('A demonstration to change the file properties');
});
> Go to the reference guide to see a list of available properties.
\ No newline at end of file
# Cell size
### Set column width
To set the column width use `->setWidth($cell, $width)`.
// Set width for a single column
$sheet->setWidth('A', 5);
// Set width for multiple cells
$sheet->setWidth(array(
'A' => 5,
'B' => 10
));
### Set row height
To set the row height use `->setHeight($row, $height)`.
// Set height for a single row
$sheet->setHeight(1, 50);
// Set height for multiple rows
$sheet->setHeight(array(
1 => 50,
2 => 25
));
### Set cell size
To set the cell size use `->setSize($cell, $width, $height)`.
// Set size for a single cell
$sheet->setSize('A1', 500, 50);
$sheet->setSize(array(
'A1' => array(
'width' => 50
'height' => 500,
)
));
\ No newline at end of file
# Store on server
To store the created file on the server, use `->store($ext, $path = false, $returnInfo = false)` or `->save()`.
### Normal export to default storage path
By default the file will be stored inside the `app/storage/exports` folder, which has been defined in the `export.php` config file.
Excel::create('Filename', function($excel) {
// Set sheets
})->store('xls');
### Normal export to custom storage path
If you want to use a custom storage path (e.g. to separate the files per client), you can set the folder as the second parameter.
->store('xls', storage_path('excel/exports'));
### Store and export
->store('xls')->export('xls');
### Store and return storage info
If you want to return storage information, set the third paramter to true or change the config setting inside `export.php`.
->store('xls', false, true);
|Key|Explanation|
|---|-----------|
|**full**| Full path with filename
|**path**| Path without filename
|**file**| Filename
|**title**| File title
|**ext**| File extension
> Make sure your storage folder is **writable**!
\ No newline at end of file
PHPExcel_Style_NumberFormat::FORMAT_GENERAL = 'General'
PHPExcel_Style_NumberFormat::FORMAT_TEXT = '@'
PHPExcel_Style_NumberFormat::FORMAT_NUMBER = '0'
PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00 = '0.00'
PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00'
PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-'
PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE = '0%'
PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00 = '0.00%'
PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd'
PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD = 'yy-mm-dd'
PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY = 'dd/mm/yy'
PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH = 'd/m/y'
PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS = 'd-m-y'
PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS = 'd-m'
PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS = 'm-y'
PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14 = 'mm-dd-yy'
PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15 = 'd-mmm-yy'
PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16 = 'd-mmm'
PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17 = 'mmm-yy'
PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22 = 'm/d/yy h:mm'
PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME = 'd/m/y h:mm'
PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1 = 'h:mm AM/PM'
PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM'
PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3 = 'h:mm'
PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4 = 'h:mm:ss'
PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5 = 'mm:ss'
PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6 = 'h:mm:ss'
PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7 = 'i:s.S'
PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8 = 'h:mm:ss;@'
PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@'
PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-'
PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD = '$#,##0_-'
PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-'
->setColumnFormat(array(
'B' => '0',
'D' => '0.00',
'F' => '@',
'F' => 'yyyy-mm-dd',
......
)
)
\ No newline at end of file
@include:Installation|installation
@include:Config|config
@include:Requirements|requirements
@include:Contributing|contributing
@include:License|license
\ No newline at end of file
#Config
### Laravel 4
Laravel Excel includes several config settings for import-, export-, view- and CSV-specific settings.
Use the artisan publish command to publish the config file to your project.
php artisan config:publish maatwebsite/excel
The config files can now be found at `app/config/packages/maatwebsite/excel`
### Laravel 5
To publish the config settings in Laravel 5 use:
php artisan vendor:publish
This will add an `excel.php` config file to your config folder.
# Contribution Guide
### Bug fixes
**ALL** bug fixes should be made to appropriate branch (e.g. `1.1` for 1.1.* bug fixes). Bug fixes should never be sent to the `master` branch.
### Pull Requests
Every pull request should pass the unit tests. If you include new functionality, make sure you include a test. Pull requests will be evaluated and possibly added to the next stable release.
### Feature Requests
If you have an idea for a new feature you would like to see added to Laravel Excel, you may create an issue on GitHub with `[Request]` in the title. The feature request will then be reviewed by @Maatwebsite.
### Coding Guidelines
Laravel, and therefore Maatwebsite's Laravel Excel follows the [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) and [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) coding standards. In addition to these standards, below is a list of other coding standards that should be followed:
- Namespace declarations should be on the same line as `<?php`.
- Class opening `{` should be on the same line as the class name.
- Function and control structure opening `{` should be on a separate line.
- Interface and Trait names are suffixed with `Interface` (`FooInterface`) and `Trait` (`FooTrait`) respectively.
#Installation
Require this package in your `composer.json` and update composer. This will download the package and PHPExcel of PHPOffice.
#### Laravel 4
"maatwebsite/excel": "~1.3"
#### Laravel 5
"maatwebsite/excel": "~2.0"
After updating composer, add the ServiceProvider to the providers array in `app/config/app.php`
'Maatwebsite\Excel\ExcelServiceProvider',
You can use the facade for shorter code. Add this to your aliasses:
'Excel' => 'Maatwebsite\Excel\Facades\Excel',
The class is binded to the ioC as `excel`
$excel = App::make('excel');
#License
This package is licensed under LGPL. You are free to use it in personal and commercial projects. The code can be forked and modified, but the original copyright author should always be included!
# Requirements
- PHP version >= 5.3.7
- Laravel >= 4.1
- PHPOffice PHPExcel >= 1.8.0 (included by composer.json)
- PHP extension php_zip enabled (required if you need PHPExcel to handle .xlsx .ods or .gnumeric files)
- PHP extension php_xml enabled
- PHP extension php_gd2 enabled (optional, but required for exact column width autocalculation)
\ No newline at end of file
@include:Importing a file|basics
@include:ExcelFile injections|injection
@include:Handling results|results
@include:Selecting sheets and columns|select
@include:Dates|dates
@include:Calculation|calculation
@include:Custom formatting values|formatting
@include:Caching and cell caching|cache
@include:Chunk importing|chunk
@include:Batch import|batch
@include:Import by config|config
@include:Edit existing files|edit
@include:Converting|convert
@include:Extra|extra
\ No newline at end of file
# Importing a file
To start importing a file, you can use `->load($filename)`. The callback is optional.
Excel::load('file.xls', function($reader) {
// reader methods
});
#Batch import
### Import a folder
To import an entire folder (only xls, xlsx and csv files will be imported), set the folder as the first parameter.
Excel::batch('app/storage/uploads', function($rows, $file) {
// Explain the reader how it should interpret each row,
// for every file inside the batch
$rows->each(function($row) {
// Example: dump the firstname
dd($row->firstname);
});
});
### Import multiple files
It's also possible to provide an array of files to import.
$files = array(
'file1.xls',
'file2.xls'
);
Excel::batch($files, function($rows, $file) {
});
### Import a folder and multiple sheets
When your files contain multiple sheets, you should also loop the sheets
Excel::batch('app/storage/uploads', function($sheets, $file) {
$sheets->each(function($sheet) {
});
});
\ No newline at end of file
# Caching and Cell caching
### Cell caching
You can enable cell caching inside the config `cache.php`. You can choose between a couple of drivers and change a couple of settings. By default the caching is **enabled** and will use **in memory** caching.
### Remembering results
If you want to remember the results you can use `->remember($minutes)`. Next time you will load the same file (if it's still inside the cache), it will return the cached results.
// Remember for 10 minutes
$results = $reader->remember(10)->get();
\ No newline at end of file
# Calculate formulas
By default formulas inside the file are being calculated and it's result will be returned. Inside `import.php` config you can change the default behaviour by setting `calculate` to the desired preference.
If you want to enable/disable it for a single import, you can use `->calculate($boolean)`
// Enable calculation
$reader->calculate();
// Disable calculation
$reader->calculate(false);
# Chunk importer
When dealing with big files, it's better to import the data in big chunks. You can enable this with `filter('chunk')`;
To import it into chunks you can use `chunk($size, $callback)` instead of the normal `get()`. The first parameter is the size of the chunk. The second parameter is a closure which will return the results.
Excel::filter('chunk')->load('file.csv')->chunk(250, function($results)
{
foreach($results as $row)
{
// do stuff
}
});
## ExcelFile class example:
When working with ExcelFile injections (in the constructor or as method injection), you can enable the chunk filter inside the ExcelFile class
class UserListImport extends \Maatwebsite\Excel\Files\ExcelFile {
public function getFile()
{
return 'file.csv';
}
public function getFilters()
{
return [
'chunk'
];
}
}
Injected ExcelFile example:
public function importUserList(UserListImport $import)
{
$import->chunk(250, function($results)
{
// do stuff
// or return true if you want to stop importing.
});
}
## Queued chunks
We automatically queue every chunk for you, if you have enabled the queue driver in your config.
If you want to by-pass the behaviour, you can pass `false` as third param of `chunk($size, $callback, $shouldQueue)`.
# Import by Config
When using advanced Excel files (e.g. without any heading columns), it can be complicated to import these.
`->byConfig()` will help you handle this problem.
Inside `excel::import.sheets` config you can find an example.
Excel::load('file.xls')->byConfig('excel::import.sheets', function($sheet) {
// The firstname getter will correspond with a cell coordinate set inside the config
$firstname = $sheet->firstname;
});
> **Note:** if you are using multiple sheets. `->byConfig` will loop through all sheets. If these getters are only exist on one sheet, you can always use `->selectSheets()`.
\ No newline at end of file
# Converting
You can convert from one filetype to another by using `->convert()`
Excel::load('file.csv', function($file) {
// modify stuff
})->convert('xls');
\ No newline at end of file
# Dates
By default the dates will be parsed as a **[Carbon object](https://github.com/briannesbitt/Carbon)**. You can disable date formatting completly inside `import.php` by setting `dates.enabled` to `false`.
To enable/disable date formatting for a single import, use `->formatDates($boolean, $format)`
// Format the dates
$reader->formatDates(true);
// Disable date formatting
$reader->formatDates(false);
// Format dates + set date format
$reader->formatDates(true, 'Y-m-d');
### Format dates
By default the dates are **not formatted**, but returned as a Carbon object. There are a couple of options to format them.
#### Formatting results after ->get()
Inside your loop you can utilise the Carbon method `->format($dateFormat)`
$rows->each(function($row) {
$created_at = $row->created_at->format('Y-m-d');
});
#### Setting a default date format
Inside the config you can set a default date format. A Carbon object will no longer be returned.
Or you can use `->setDateFormat()`
$reader->setDateFormat('Y-m-d');
### Setting custom date columns
Cells which are not Excel formatted dates will not be parsed as a date. To force this behaviour (or to use this with CSV imports), you can set these date columns manually: `->setDateColumns()`
$reader->setDateColumns(array(
'created_at',
'deleted_at'
))->get();
# Editing existing files
You can edit existing Excel files, by loading them and after modification exporting them.
Excel::load('file.csv', function($file) {
// modify stuff
})->export('csv');
# Extra
### Disable using first row as collection attributes
By default we will use the first row of a file as table heading (so as attribute names for the collection).
You can change the default behaviour inside `import.php` with `import.heading`.
To disable this for a single import, use `->noHeading()`.
$reader->noHeading();
### Setting the cell name separator
By default collection attribute names will be set by looking at the first row columns. Spaces will be translated to `_`.
**E.g. Created at -> created_at**
The default behaviour can be changed inside the `import.php` config by changing `'separator'`. Or you can use `->setSeparator($separator)`.
$reader->setSeparator('-');
### Ignoring empty cells
By default empty cells will not be ignored and presented as null inside the cell collection.
To change the default behaviour, you can change `'ignoreEmpty`' inside `import.php` or use `->ignoreEmpty()`.
$reader->ignoreEmpty();
### Input encoding
Inside the `import.php` config you can change the input encoding. In most cases **UTF-8** will be the best solution. Hower if you dump your results make sure your HTML page has this exact same meta charset!
Optionally you can pass the input encoding inside the `->load()` method.
// When utilising a closure, you can pass the input encoding as third parameter.
Excel::load('filename.csv', function($reader) {
}, 'UTF-8');
// or without a closure, you can use it as second parameter.
Excel::load('filename.csv', 'UTF-8');
### CSV Settings
Inside the `csv.php` config you can change the default settings, like the `delimiter`, the `enclosure` and the `line_ending`.
# Custom formatting values
By default Laravel Excel uses PHPExcel's default value binder to intelligently format a cells value when reading it. You may override this behavior by passing in your own value binder to suit your specific needs. Value binders must implement PHPExcel_Cell_IValueBinder and have a bindValue method. They may also extend PHPExcel_Cell_DefaultValueBinder to return the default behavior.
use PHPExcel_Cell;
use PHPExcel_Cell_DataType;
use PHPExcel_Cell_IValueBinder;
use PHPExcel_Cell_DefaultValueBinder;
class MyValueBinder extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
{
public function bindValue(PHPExcel_Cell $cell, $value = null)
{
if (is_numeric($value))
{
$cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
return true;
}
// else return default behavior
return parent::bindValue($cell, $value);
}
}
$myValueBinder = new MyValueBinder;
Excel::setValueBinder($myValueBinder)->load('file.xls', function($reader) {
// reader methods
});
Available PHPExcel_Cell_DataType's are TYPE_STRING, TYPE_FORMULA, TYPE_NUMERIC, TYPE_BOOL, TYPE_NULL, TYPE_INLINE and TYPE_ERROR
To reset the value binder back to default and/or before calling Laravel Excel after setting a custom value binder you need to call the resetValueBinder method.
Excel::resetValueBinder();
\ No newline at end of file
# ExcelFile injections
Following the Laravel 5.0 philosophy with its new awesome FormRequest injections, we introduce you ExcelFile injections.
## ExcelFile class
This class is a wrapper for a file on your server. Inside the `getFile()` method you return the filename and it's location. Inside the `getFilters()` method you can enable filters, like the chunk filter.
class UserListImport extends \Maatwebsite\Excel\Files\ExcelFile {
public function getFile()
{
return storage_path('exports') . '/file.csv';
}
public function getFilters()
{
return [
'chunk'
];
}
}
If you want to have the `getFile()` dynamic based on user's input, you can easily do:
public function getFile()
{
// Import a user provided file
$file = Input::file('report');
$filename = $this->doSomethingLikeUpload($file);
// Return it's location
return $filename;
}
## Usage
You can inject these ExcelFiles inside the __constructor or inside the method (when using Laravel 5.0), in e.g. the controller.
class ExampleController extends Controller {
public function importUserList(UserListImport $import)
{
// get the results
$results = $import->get();
}
}
## CSV Settings
You can pass through optional CSV settings, like `$delimiter`, `$enclosure` and `$lineEnding` as protected properties of the class.
class UserListImport extends \Maatwebsite\Excel\Files\ExcelFile {
protected $delimiter = ',';
protected $enclosure = '"';
protected $lineEnding = '\r\n';
}
## Import Handlers
To decouple your Excel-import code completely from the controller, you can use the import handlers.
class ExampleController extends Controller {
public function importUserList(UserListImport $import)
{
// Handle the import
$import->handleImport();
}
}
The `handleImport()` method will dynamically call a handler class which is your class name appended with `Handler`
class UserListImportHandler implements \Maatwebsite\Excel\Files\ImportHandler {
public function handle(UserListImport $import)
{
// get the results
$results = $import->get();
}
}
# Handling imported results
### Getting all sheets and rows
After you have loaded a file, you can `->get()` the results like so:
Excel::load('file.xls', function($reader) {
})->get();
or
Excel::load('file.xls', function($reader) {
// Getting all results
$results = $reader->get();
// ->all() is a wrapper for ->get() and will work the same
$results = $reader->all();
});
> The `->get()` and `->all()` methods will return a sheet or row collection, depending on the amount of sheets the file has. You can disable this feature inside the `import.php` config by setting `'force_sheets_collection'` to `true`. When set to true it will always return a sheet collection.
### Table heading as attributes
By default the first row of the excel file will be used as attributes.
// Get the firstname
$row->firstname;
> **Note**: by default these attributes will be converted to a slug. You can change the default inside the config `excel::import.heading`. Available options are: `true|false|slugged|ascii|numeric|hashed|trans|original`
> True and slugged will be converted to ASCII as well when `excel::import.to_ascii` is set to true. You can change the default separator as well inside the config.
### Collections
Sheets, rows and cells are collections, this means after doing a `->get()` you can use all default collection methods.
// E.g. group the results
$reader->get()->groupBy('firstname');
### Getting the first sheet or row
To get the first sheet or row, you can utilise `->first()`.
$reader->first();
> **Note:** depending on the config `'force_sheets_collection'` it will return the first row or sheet.
### Workbook and sheet title
It's possible to retrieve the workbook and sheet title with `->getTitle()`.
// Get workbook title
$workbookTitle = $reader->getTitle();
foreach($reader as $sheet)
{
// get sheet title
$sheetTitle = $sheet->getTitle();
}
### Limiting the results
##### Taking rows
When you only want to return the first x rows of a sheet, you can use `->take()` or `->limit()`.
// You can either use ->take()
$reader->take(10);
// Or ->limit()
$reader->limit(10);
##### Skipping rows
When you want to skip a certain amount of rows you can use `->skip()` or `->limit(false, 10)`
// Skip 10 results
$reader->skip(10);
// Skip 10 results with limit, but return all other rows
$reader->limit(false, 10);
// Skip and take
$reader->skip(10)->take(10);
// Limit with skip and take
$reader->($skip, $take);
### Result mutators
When you want to get an array instead of an object, you can use `->toArray()`.
$reader->toArray();
When you want an object, you can alternativly (instead of get() or all()) use `->toObject()`.
$reader->toObject();
### Displaying results
You can dump the results to a readable output by using `->dump()` or `->dd()`.
// Dump the results
$reader->dump();
// Dump results and die
$reader->dd();
### Iterating the results
You can iterate the results by using `->each()`.
// Loop through all sheets
$reader->each(function($sheet) {
// Loop through all rows
$sheet->each(function($row) {
});
});
> Alternatively you can also `foreach` the results.
# Selecting sheets and columns
### Selecting one specific sheet
If you want to select a single sheet, you can use `->selectSheets($name)`. Only that sheet will be loaded.
Excel::selectSheets('sheet1')->load();
### Selecting multiple sheets
If you want to select multiple sheets inside your file, you can pass an array as the parameter;
Excel::selectSheets('sheet1', 'sheet2')->load();
### Selecting sheets by index
// First sheet
Excel::selectSheetsByIndex(0)->load();
// First and second sheet
Excel::selectSheetsByIndex(0, 1)->load();
### Selecting columns
If you want to select only a couple of columns, you can use `->select($columns)` or pass an array as the first parameter of `->get($columns)`.
// Select
$reader->select(array('firstname', 'lastname'))->get();
// Or
$reader->get(array('firstname', 'lastname'));
> All get methods (like all(), first(), dump(), toArray(), ...) accept an array of columns.
$mergeColumn = array(
* 'columns' => array('A','B','C','D'),
* 'rows' => array(
* array(2,3),
* array(5,11),
* .....
* )
* );
\ No newline at end of file
@include:Available file properties|file-properties
@include:Available sheet properties|sheet-properties
@include:Available CSS styles|css-styles
@include:Available border styles|borders
@include:Available column formatting|formatting
@include:Closures|closures
\ No newline at end of file
# Available border styles
| Style name | PHPExcel class reference|
| ------------- |-----------------|
|none|PHPExcel_Style_Border::BORDER_NONE
|dashDot|PHPExcel_Style_Border::BORDER_DASHDOT
| dashDotDot|PHPExcel_Style_Border::BORDER_DASHDOTDOT
| dashed |PHPExcel_Style_Border::BORDER_DASHED
| dotted |PHPExcel_Style_Border::BORDER_DOTTED
| double |PHPExcel_Style_Border::BORDER_DOUBLE
| hair |PHPExcel_Style_Border::BORDER_HAIR
| medium |PHPExcel_Style_Border::BORDER_MEDIUM
| mediumDashDot |PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT
| mediumDashDotDot |PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT
| mediumDashed |PHPExcel_Style_Border::BORDER_MEDIUMDASHED
| slantDashDot |PHPExcel_Style_Border::BORDER_SLANTDASHDOT
| thick|PHPExcel_Style_Border::BORDER_THICK
| thin|PHPExcel_Style_Border::BORDER_THIN
\ No newline at end of file
# Closures
| Method | Closure class |
| ------------- |-------------|
| create() | Maatwebsite\Excel\Writers\LaravelExcelWriter |
| load() | Maatwebsite\Excel\Readers\LaravelExcelReader |
| batch | Maatwebsite\Excel\Readers\Batch |
| sheet() | Maatwebsite\Excel\Classes\LaravelExcelWorksheet |
| cells() | Maatwebsite\Excel\Writers\CellWriter |
| row() | Maatwebsite\Excel\Writers\CellWriter |
\ No newline at end of file
# Available CSS styles
Styles that can be used inside an external CSS file or as inline CSS.
| Style name | Example Value |
| ------------- |-------------|
| background(-color) | #000000 |
| color | #FFFFFF |
| font-weight | bold |
| font-style | italic |
| font-weight | bold |
| font-size | 20px |
| font-family | Open Sans |
| text-decoration | underline |
| text-align | center |
| vertical-align | middle |
| border(-*) | 1px dashed #CCC |
| width | 100(px) |
| height | 1100(px) |
\ No newline at end of file
# Available file properties
Properties that can be set with `$excel->set{$property}()`
| Property name |
| ------------- |
|creator
|lastModifiedBy
|title
|description
|subject
|keywords
|category
|manager
|company
\ No newline at end of file
# Available column formatting
| Format name | PHPExcel class reference|
| ------------- |-----------------|
|General|PHPExcel_Style_NumberFormat::FORMAT_GENERAL
|@|PHPExcel_Style_NumberFormat::FORMAT_TEXT
|0|PHPExcel_Style_NumberFormat::FORMAT_NUMBER
|0.00|PHPExcel_Style_NumberFormat::FORMAT_NUMBER_00
|#,##0.00|PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1
|#,##0.00_-|PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED2
|0%|PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE
|0.00%|PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00
|yyyy-mm-dd|PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2
|yy-mm-dd|PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD
|dd/mm/yy|PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY
|d/m/y|PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH
|d-m-y|PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS
|d-m|PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS
|m-y|PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS
|mm-dd-yy|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14
|d-mmm-yy|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15
|d-mmm|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16
|mmm-yy|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17
|m/d/yy h:mm|PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22
|d/m/y h:mm|PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME
|h:mm AM/PM|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1
|h:mm:ss AM/PM|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2
|h:mm|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3
|h:mm:ss|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4
|mm:ss|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5
|h:mm:ss|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6
|i:s.S|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7
|h:mm:ss;@|PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8
|yy/mm/dd;@|PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH
|"$"#,##0.00_-|PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE
|$#,##0_-|PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD
|[$EUR ]#,##0.00_-|PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
\ No newline at end of file
# Available sheet properties
Properties that can be set with `$sheet->set{$property}()`
| Property name | Possible value|
| ------------- |-----------------|
|orientation| string
|paperSize| integer
|scale| integer
|fitToPage| boolean
|fitToHeight| boolean
|fitToWidth| boolean
|columnsToRepeatAtLeft| array
|rowsToRepeatAtTop| array
|horizontalCentered| boolean
|verticalCentered| boolean
|printArea| range
|firstPageNumber| integer
\ No newline at end of file
REDIS0006ܳCZV
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_KEY" value="AckfSECXIvnK5r28GVIWUAxmbBSjTsmF"/>
</php>
</phpunit>
{
"providers": [
"Maatwebsite\\Excel\\ExcelServiceProvider"
],
"aliases": [
{
"alias": "Excel",
"facade": "Maatwebsite\\Excel\\Facades\\Excel"
}
]
}
<?php namespace Maatwebsite\Excel\Classes;
use PHPExcel_Settings;
use Illuminate\Support\Facades\Config;
use PHPExcel_CachedObjectStorageFactory;
class Cache {
/**
* PHPExcel cache class
* @var string
*/
protected $class = 'PHPExcel_CachedObjectStorageFactory';
/**
* Available caching drivers
* @var array
*/
protected $available = array(
'memory' => 'cache_in_memory',
'gzip' => 'cache_in_memory_gzip',
'serialized' => 'cache_in_memory_serialized',
'igbinary' => 'cache_igbinary',
'discISAM' => 'cache_to_discISAM',
'apc' => 'cache_to_apc',
'memcache' => 'cache_to_memcache',
'temp' => 'cache_to_phpTemp',
'wincache' => 'cache_to_wincache',
'sqlite' => 'cache_to_sqlite',
'sqlite3' => 'cache_to_sqlite3'
);
/**
* The name of the config file
* @var string
*/
private $configName = 'excel.cache';
/**
* Cache constructor
*/
public function __construct()
{
// Get driver and settings from the config
$this->driver = Config::get($this->configName . '.driver', 'memory');
$this->settings = Config::get($this->configName . '.settings', array());
// Init if caching is enabled
if ($this->isEnabled())
$this->init();
}
/**
* Init the cache
* @return void
*/
public function init()
{
// Find the cache driver
$this->findDriver();
// Set the storage driver
PHPExcel_Settings::setCacheStorageMethod($this->method, $this->settings);
}
/**
* Set the right driver
* @return void
*/
public function findDriver()
{
$property = $this->detect();
$this->method = constant($this->class . '::' . $property);
}
/**
* Detect the caching driver
* @return string $driver
*/
protected function detect()
{
// Add additional settings
$this->addAdditionalSettings();
// return the driver
return isset($this->available[$this->driver]) ? $this->available[$this->driver] : reset($this->available);
}
/**
* Add additional settings for the current driver
* @return void
*/
protected function addAdditionalSettings()
{
switch ($this->driver)
{
case 'memcache':
// Add extra memcache settings
$this->settings = array_merge($this->settings, array(
'memcacheServer' => Config::get($this->configName . '.memcache.host', 'localhost'),
'memcachePort' => Config::get($this->configName . '.memcache.port', 11211)
));
break;
case 'discISAM':
// Add dir
$this->settings = array_merge($this->settings, array(
'dir' => Config::get($this->configName . '.dir', storage_path('cache')),
));
break;
}
}
/**
* Check if caching is enabled
* @return boolean
*/
public function isEnabled()
{
return Config::get($this->configName . '.enable', true) ? true : false;
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Classes;
use PHPExcel_IOFactory;
use Illuminate\Filesystem\Filesystem;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
class FormatIdentifier {
/**
* Available formats
*
* @var array
* @access protected
*/
protected $formats = array(
'Excel2007',
'Excel5',
'Excel2003XML',
'OOCalc',
'SYLK',
'Gnumeric',
'CSV',
'HTML',
'PDF'
);
/**
* Construct new format identifier
* @param Filesystem $filesystem
*/
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* Get the file format by file
* @param $file
* @throws LaravelExcelException
* @return string $format
*/
public function getFormatByFile($file)
{
// get the file extension
$ext = $this->getExtension($file);
// get the file format
$format = $this->getFormatByExtension($ext);
// Check if the file can be read
if ($this->canRead($format, $file))
return $format;
// Do a last try to init the file with all available readers
return $this->lastResort($file, $format, $ext);
}
/**
* Identify file format
* @param $ext
* @return string $format
*/
public function getFormatByExtension($ext)
{
switch ($ext)
{
/*
|--------------------------------------------------------------------------
| Excel 2007
|--------------------------------------------------------------------------
*/
case 'xlsx':
case 'xlsm':
case 'xltx':
case 'xltm':
return 'Excel2007';
break;
/*
|--------------------------------------------------------------------------
| Excel5
|--------------------------------------------------------------------------
*/
case 'xls':
case 'xlt':
return 'Excel5';
break;
/*
|--------------------------------------------------------------------------
| OOCalc
|--------------------------------------------------------------------------
*/
case 'ods':
case 'ots':
return 'OOCalc';
break;
/*
|--------------------------------------------------------------------------
| SYLK
|--------------------------------------------------------------------------
*/
case 'slk':
return 'SYLK';
break;
/*
|--------------------------------------------------------------------------
| Excel2003XML
|--------------------------------------------------------------------------
*/
case 'xml':
return 'Excel2003XML';
break;
/*
|--------------------------------------------------------------------------
| Gnumeric
|--------------------------------------------------------------------------
*/
case 'gnumeric':
return 'Gnumeric';
break;
/*
|--------------------------------------------------------------------------
| HTML
|--------------------------------------------------------------------------
*/
case 'htm':
case 'html':
return 'HTML';
break;
/*
|--------------------------------------------------------------------------
| CSV
|--------------------------------------------------------------------------
*/
case 'csv':
case 'txt':
return 'CSV';
break;
/*
|--------------------------------------------------------------------------
| PDF
|--------------------------------------------------------------------------
*/
case 'pdf':
return 'PDF';
break;
}
}
/**
* Get the content type by file format
* @param string $format
* @return string $contentType
*/
public function getContentTypeByFormat($format)
{
switch ($format)
{
/*
|--------------------------------------------------------------------------
| Excel 2007
|--------------------------------------------------------------------------
*/
case 'Excel2007':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8';
break;
/*
|--------------------------------------------------------------------------
| Excel5
|--------------------------------------------------------------------------
*/
case 'Excel5':
return 'application/vnd.ms-excel; charset=UTF-8';
break;
/*
|--------------------------------------------------------------------------
| HTML
|--------------------------------------------------------------------------
*/
case 'HTML':
return 'HTML';
break;
/*
|--------------------------------------------------------------------------
| CSV
|--------------------------------------------------------------------------
*/
case 'CSV':
return 'application/csv; charset=UTF-8';
break;
/*
|--------------------------------------------------------------------------
| PDF
|--------------------------------------------------------------------------
*/
case 'PDF':
return'application/pdf; charset=UTF-8';
break;
}
}
/**
* Try every reader we have
* @param $file
* @param bool $wrongFormat
* @param string $ext
* @throws LaravelExcelException
* @return string $format
*/
protected function lastResort($file, $wrongFormat = false, $ext = 'xls')
{
// Loop through all available formats
foreach ($this->formats as $format)
{
// Check if the file could be read
if ($wrongFormat != $format && $this->canRead($format, $file))
return $format;
}
// Give up searching and throw an exception
throw new LaravelExcelException('[ERROR] Reader could not identify file format for file [' . $file . '] with extension [' . $ext . ']');
}
/**
* Check if we can read the file
* @param $format
* @param $file
* @return boolean
*/
protected function canRead($format, $file)
{
if ($format)
{
$reader = $this->initReader($format);
return $reader && $reader->canRead($file);
}
return false;
}
/**
* Init the reader based on the format
* @param string $format
* @return \PHPExcel_Reader_IReader
*/
protected function initReader($format)
{
return PHPExcel_IOFactory::createReader($format);
}
/**
* Get the file extension
* @param string $file
* @return string
*/
protected function getExtension($file)
{
return strtolower($this->filesystem->extension($file));
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Classes;
use PHPExcel as PHPOffice_PHPExcel;
use Illuminate\Support\Facades\Config;
/**
*
* Laravel wrapper for PHPExcel
*
* @category Laravel Excel
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @copyright Original Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class PHPExcel extends PHPOffice_PHPExcel {
/**
* Allowed autofill properties
* @var array
*/
public $allowedProperties = array(
'creator',
'lastModifiedBy',
'description',
'subject',
'keywords',
'category',
'manager',
'company'
);
/**
* Create sheet and add it to this workbook
*
* @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
* @param bool|string $title
* @throws \PHPExcel_Exception
* @return LaravelExcelWorksheet
*/
public function createSheet($iSheetIndex = null, $title = false)
{
// Init new Laravel Excel worksheet
$newSheet = new LaravelExcelWorksheet($this, $title);
// Add the sheet
$this->addSheet($newSheet, $iSheetIndex);
// Return the sheet
return $newSheet;
}
/**
* Check if the user change change the workbook property
* @param string $method
* @return boolean
*/
public function isChangeableProperty($method)
{
$name = lcfirst(str_replace('set', '', $method));
return in_array($name, $this->getAllowedProperties()) ? true : false;
}
/**
* Set default properties
* @param array $custom
* @return void
*/
public function setDefaultProperties($custom = [])
{
// Get the properties
$properties = $this->getProperties();
// Get fillable properties
foreach ($this->getAllowedProperties() as $prop)
{
// Get the method
$method = 'set' . ucfirst($prop);
// get the value
$value = in_array($prop, array_keys($custom)) ? $custom[$prop] : Config::get('excel.properties.' . $prop, null);
// set the property
call_user_func_array(array($properties, $method), array($value));
}
}
/**
* load info from parent obj
* @param \PHPExcel $object
* @return $this
*/
function cloneParent(\PHPExcel $object)
{
// Init new reflection object
$class = new \ReflectionClass(get_class($object));
// Loop through all properties
foreach($class->getProperties() as $property)
{
// Make the property public
$property->setAccessible(true);
// Set the found value to this sheet
$property->setValue(
$this,
$property->getValue($object)
);
}
return $this;
}
/**
* Return all allowed properties
* @return array
*/
public function getAllowedProperties()
{
return $this->allowedProperties;
}
}
<?php namespace Maatwebsite\Excel\Collections;
/**
*
* LaravelExcel CellCollection
*
* @category Laravel Excel
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class CellCollection extends ExcelCollection {
/**
* Create a new collection.
* @param array $items
* @return \Maatwebsite\Excel\Collections\CellCollection
*/
public function __construct(array $items = array())
{
$this->setItems($items);
}
/**
* Set the items
* @param array $items
* @return void
*/
public function setItems($items)
{
foreach ($items as $name => $value)
{
$value = !empty($value) || is_numeric($value) ? $value : null;
if ($name && !is_numeric($name))
{
$this->put($name, $value);
}
else
{
$this->push($value);
}
}
}
/**
* Dynamically get values
* @param string $key
* @return string
*/
public function __get($key)
{
if ($this->has($key))
return $this->get($key);
}
/**
* Determine if an attribute exists on the model.
*
* @param string $key
* @return bool
*/
public function __isset($key)
{
return $this->has($key);
}
}
<?php namespace Maatwebsite\Excel\Collections;
use Illuminate\Support\Collection;
/**
*
* LaravelExcel ExcelCollection
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class ExcelCollection extends Collection {
/**
* Sheet title
* @var [type]
*/
protected $title;
/**
* Get the title
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set the title
* @param $title
*/
public function setTitle($title)
{
$this->title = $title;
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Collections;
/**
*
* LaravelExcel RowCollection
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class RowCollection extends ExcelCollection {
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Collections;
/**
*
* LaravelExcel SheetCollection
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class SheetCollection extends ExcelCollection {
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel;
use Closure;
use Maatwebsite\Excel\Readers\Batch;
use Maatwebsite\Excel\Classes\PHPExcel;
use Maatwebsite\Excel\Readers\LaravelExcelReader;
use Maatwebsite\Excel\Writers\LaravelExcelWriter;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
/**
*
* Laravel wrapper for PHPExcel
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class Excel {
/**
* Filter
* @var array
*/
protected $filters = array(
'registered' => array(),
'enabled' => array()
);
/**
* Excel object
* @var PHPExcel
*/
protected $excel;
/**
* Reader object
* @var LaravelExcelReader
*/
protected $reader;
/**
* Writer object
* @var LaravelExcelWriter
*/
protected $writer;
/**
* Construct Excel
* @param PHPExcel $excel
* @param LaravelExcelReader $reader
* @param LaravelExcelWriter $writer
*/
public function __construct(PHPExcel $excel, LaravelExcelReader $reader, LaravelExcelWriter $writer)
{
// Set Excel dependencies
$this->excel = $excel;
$this->reader = $reader;
$this->writer = $writer;
}
/**
* Create a new file
* @param $filename
* @param callable|null $callback
* @return LaravelExcelWriter
*/
public function create($filename, $callback = null)
{
// Writer instance
$writer = clone $this->writer;
// Disconnect worksheets to prevent unnecessary ones
$this->excel->disconnectWorksheets();
// Inject our excel object
$writer->injectExcel($this->excel);
// Set the filename and title
$writer->setFileName($filename);
$writer->setTitle($filename);
// Do the callback
if ($callback instanceof Closure)
call_user_func($callback, $writer);
// Return the writer object
return $writer;
}
/**
*
* Load an existing file
*
* @param string $file The file we want to load
* @param callback|null $callback
* @param string|null $encoding
* @param bool $noBasePath
* @return LaravelExcelReader
*/
public function load($file, $callback = null, $encoding = null, $noBasePath = false)
{
// Reader instance
$reader = clone $this->reader;
// Inject excel object
$reader->injectExcel($this->excel);
// Enable filters
$reader->setFilters($this->filters);
// Set the encoding
$encoding = is_string($callback) ? $callback : $encoding;
// Start loading
$reader->load($file, $encoding, $noBasePath);
// Do the callback
if ($callback instanceof Closure)
call_user_func($callback, $reader);
// Return the reader object
return $reader;
}
/**
* Set select sheets
* @param $sheets
* @return LaravelExcelReader
*/
public function selectSheets($sheets = array())
{
$sheets = is_array($sheets) ? $sheets : func_get_args();
$this->reader->setSelectedSheets($sheets);
return $this;
}
/**
* Select sheets by index
* @param array $sheets
* @return $this
*/
public function selectSheetsByIndex($sheets = array())
{
$sheets = is_array($sheets) ? $sheets : func_get_args();
$this->reader->setSelectedSheetIndices($sheets);
return $this;
}
/**
* Batch import
* @param $files
* @param callback $callback
* @return PHPExcel
*/
public function batch($files, Closure $callback)
{
$batch = new Batch;
return $batch->start($this, $files, $callback);
}
/**
* Create a new file and share a view
* @param string $view
* @param array $data
* @param array $mergeData
* @return LaravelExcelWriter
*/
public function shareView($view, $data = array(), $mergeData = array())
{
return $this->create($view)->shareView($view, $data, $mergeData);
}
/**
* Create a new file and load a view
* @param string $view
* @param array $data
* @param array $mergeData
* @return LaravelExcelWriter
*/
public function loadView($view, $data = array(), $mergeData = array())
{
return $this->shareView($view, $data, $mergeData);
}
/**
* Set filters
* @param array $filters
* @return Excel
*/
public function registerFilters($filters = array())
{
// If enabled array key exists
if(array_key_exists('enabled', $filters))
{
// Set registered array
$registered = $filters['registered'];
// Filter on enabled
$this->filter($filters['enabled']);
}
else
{
$registered = $filters;
}
// Register the filters
$this->filters['registered'] = !empty($this->filters['registered']) ? array_merge($this->filters['registered'], $registered) : $registered;
return $this;
}
/**
* Enable certain filters
* @param string|array $filter
* @param bool|false|string $class
* @return Excel
*/
public function filter($filter, $class = false)
{
// Add multiple filters
if(is_array($filter))
{
$this->filters['enabled'] = !empty($this->filters['enabled']) ? array_merge($this->filters['enabled'], $filter) : $filter;
}
else
{
// Add single filter
$this->filters['enabled'][] = $filter;
// Overrule filter class for this request
if($class)
$this->filters['registered'][$filter] = $class;
}
// Remove duplicates
$this->filters['enabled'] = array_unique($this->filters['enabled']);
return $this;
}
/**
* Get register, enabled (or both) filters
* @param string|boolean $key [description]
* @return array
*/
public function getFilters($key = false)
{
return $key ? $this->filters[$key] : $this->filters;
}
/**
* Dynamically call methods
* @throws LaravelExcelException
*/
public function __call($method, $params)
{
// If the dynamic call starts with "with", add the var to the data array
if (method_exists($this->excel, $method))
{
// Call the method from the excel object with the given params
return call_user_func_array(array($this->excel, $method), $params);
}
// If reader method exists, call that one
if (method_exists($this->reader, $method))
{
// Call the method from the reader object with the given params
return call_user_func_array(array($this->reader, $method), $params);
}
throw new LaravelExcelException('Laravel Excel method [' . $method . '] does not exist');
}
}
<?php namespace Maatwebsite\Excel;
use PHPExcel_Settings;
use PHPExcel_Shared_Font;
use Maatwebsite\Excel\Readers\Html;
use Maatwebsite\Excel\Classes\Cache;
use Illuminate\Support\Facades\Config;
use Maatwebsite\Excel\Classes\PHPExcel;
use Illuminate\Support\ServiceProvider;
use Maatwebsite\Excel\Parsers\CssParser;
use Maatwebsite\Excel\Parsers\ViewParser;
use Maatwebsite\Excel\Classes\FormatIdentifier;
use Maatwebsite\Excel\Readers\LaravelExcelReader;
use Maatwebsite\Excel\Writers\LaravelExcelWriter;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
/**
*
* LaravelExcel Excel ServiceProvider
*
* @category Laravel Excel
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class ExcelServiceProvider extends ServiceProvider {
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__ . '/../../config/excel.php' => config_path('excel.php'),
]);
$this->mergeConfigFrom(
__DIR__ . '/../../config/excel.php', 'excel'
);
//Set the autosizing settings
$this->setAutoSizingSettings();
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->bindClasses();
$this->bindCssParser();
$this->bindReaders();
$this->bindParsers();
$this->bindPHPExcelClass();
$this->bindWriters();
$this->bindExcel();
}
/**
* Bind PHPExcel classes
* @return void
*/
protected function bindPHPExcelClass()
{
// Set object
$me = $this;
// Bind the PHPExcel class
$this->app['phpexcel'] = $this->app->share(function () use ($me)
{
// Set locale
$me->setLocale();
// Set the caching settings
$me->setCacheSettings();
// Init phpExcel
$excel = new PHPExcel();
$excel->setDefaultProperties();
return $excel;
});
}
/**
* Bind the css parser
*/
protected function bindCssParser()
{
// Bind css parser
$this->app['excel.parsers.css'] = $this->app->share(function ()
{
return new CssParser(
new CssToInlineStyles()
);
});
}
/**
* Bind writers
* @return void
*/
protected function bindReaders()
{
// Bind the laravel excel reader
$this->app['excel.reader'] = $this->app->share(function ($app)
{
return new LaravelExcelReader(
$app['files'],
$app['excel.identifier']
);
});
// Bind the html reader class
$this->app['excel.readers.html'] = $this->app->share(function ($app)
{
return new Html(
$app['excel.parsers.css']
);
});
}
/**
* Bind writers
* @return void
*/
protected function bindParsers()
{
// Bind the view parser
$this->app['excel.parsers.view'] = $this->app->share(function ($app)
{
return new ViewParser(
$app['excel.readers.html']
);
});
}
/**
* Bind writers
* @return void
*/
protected function bindWriters()
{
// Bind the excel writer
$this->app['excel.writer'] = $this->app->share(function ($app)
{
return new LaravelExcelWriter(
$app->make('Response'),
$app['files'],
$app['excel.identifier']
);
});
}
/**
* Bind Excel class
* @return void
*/
protected function bindExcel()
{
// Bind the Excel class and inject its dependencies
$this->app['excel'] = $this->app->share(function ($app)
{
$excel = new Excel(
$app['phpexcel'],
$app['excel.reader'],
$app['excel.writer'],
$app['excel.parsers.view']
);
$excel->registerFilters($app['config']->get('excel.filters', array()));
return $excel;
});
}
/**
* Bind other classes
* @return void
*/
protected function bindClasses()
{
// Bind the format identifier
$this->app['excel.identifier'] = $this->app->share(function ($app)
{
return new FormatIdentifier($app['files']);
});
}
/**
* Set cache settings
* @return Cache
*/
public function setCacheSettings()
{
return new Cache();
}
/**
* Set locale
*/
public function setLocale()
{
$locale = Config::get('app.locale', 'en_us');
PHPExcel_Settings::setLocale($locale);
}
/**
* Set the autosizing settings
*/
public function setAutoSizingSettings()
{
$method = Config::get('excel.export.autosize-method', PHPExcel_Shared_Font::AUTOSIZE_METHOD_APPROX);
PHPExcel_Shared_Font::setAutoSizeMethod($method);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array(
'excel',
'phpexcel',
'excel.reader',
'excel.readers.html',
'excel.parsers.view',
'excel.writer'
);
}
}
<?php namespace Maatwebsite\Excel\Exceptions;
use PHPExcel_Exception;
/**
*
* LaravelExcel Exception
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class LaravelExcelException extends PHPExcel_Exception {
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Facades;
use Illuminate\Support\Facades\Facade;
/**
*
* LaravelExcel Facade
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class Excel extends Facade {
/**
* Return facade accessor
* @return string
*/
protected static function getFacadeAccessor()
{
return 'excel';
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Files;
use Illuminate\Foundation\Application;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
abstract class ExcelFile extends File {
/**
* @var bool|string
*/
protected $delimiter;
/**
* @var bool|string
*/
protected $enclosure;
/**
* @var null
*/
protected $encoding = null;
/**
* @param Application $app
* @param Excel $excel
*/
public function __construct(Application $app, Excel $excel)
{
parent::__construct($app, $excel);
$this->file = $this->loadFile();
}
/**
* Get file
* @return string
*/
abstract public function getFile();
/**
* Get delimiter
* @return string
*/
protected function getDelimiter()
{
return $this->delimiter;
}
/**
* Get enclosure
* @return string
*/
protected function getEnclosure()
{
return $this->enclosure;
}
/**
* Get filters
* @return array
*/
public function getFilters()
{
return [];
}
/**
* Start importing
*/
public function handleImport()
{
return $this->handle(
get_class($this)
);
}
/**
* Load the file
* @return \Maatwebsite\Excel\Readers\LaravelExcelReader
*/
public function loadFile()
{
// Load filters
$this->loadFilters();
// Load base settings
$this->loadBaseSettings();
// Load the file
$file = $this->excel->load(
$this->getFile(),
null,
$this->encoding
);
return $file;
}
/**
* Load the filter
* @return void
*/
protected function loadFilters()
{
// Register the filters
$this->excel->registerFilters(
$this->getFilters()
);
// Loop through the filters
foreach($this->getFilters() as $filter)
{
// Enable the filter
$this->excel->filter($filter);
}
}
/**
* Load base settings
*/
protected function loadBaseSettings()
{
$this->loadCSVSettings();
}
/**
* Load CSV Settings
*/
protected function loadCSVSettings()
{
// Get user provided delimiter
$delimiter = $this->getDelimiter();
// Set it when given
if($delimiter)
$this->excel->setDelimiter($delimiter);
// Get user provided enclosure
$enclosure = $this->getEnclosure();
// Set it when given
if($enclosure)
$this->excel->setEnclosure($enclosure);
}
/**
* Dynamically call methods
* @param string $method
* @param array $params
* @return mixed
*/
public function __call($method, $params)
{
return call_user_func_array([$this->file, $method], $params);
}
}
<?php namespace Maatwebsite\Excel\Files;
interface ExportHandler {
/**
* Handle the export
* @param $file
* @return mixed
*/
public function handle($file);
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Files;
use Illuminate\Foundation\Application;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
abstract class File {
/**
* @var Application
*/
protected $app;
/**
* Excel instance
* @var Excel
*/
protected $excel;
/**
* Loaded file
* @var \Maatwebsite\Excel\Readers\LaravelExcelReader
*/
protected $file;
/**
* @param Application $app
* @param Excel $excel
*/
public function __construct(Application $app, Excel $excel)
{
$this->app = $app;
$this->excel = $excel;
}
/**
* Handle the import/export of the file
* @param $type
* @throws LaravelExcelException
* @return mixed
*/
public function handle($type)
{
// Get the handler
$handler = $this->getHandler($type);
// Call the handle method and inject the file
return $handler->handle($this);
}
/**
* Get handler
* @param $type
* @throws LaravelExcelException
* @return mixed
*/
protected function getHandler($type)
{
return $this->app->make(
$this->getHandlerClassName($type)
);
}
/**
* Get the file instance
* @return mixed
*/
public function getFileInstance()
{
return $this->file;
}
/**
* Get the handler class name
* @throws LaravelExcelException
* @return string
*/
protected function getHandlerClassName($type)
{
// Translate the file into a FileHandler
$class = get_class($this);
$handler = substr_replace($class, $type . 'Handler', strrpos($class, $type));
// Check if the handler exists
if (!class_exists($handler))
throw new LaravelExcelException("$type handler [$handler] does not exist.");
return $handler;
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Files;
interface ImportHandler {
/**
* Handle the import
* @param $file
* @return mixed
*/
public function handle($file);
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Files;
use Illuminate\Foundation\Application;
use Maatwebsite\Excel\Excel;
abstract class NewExcelFile extends File {
/**
* @param Application $app
* @param Excel $excel
*/
public function __construct(Application $app, Excel $excel)
{
parent::__construct($app, $excel);
$this->file = $this->createNewFile();
}
/**
* Get file
* @return string
*/
abstract public function getFilename();
/**
* Start importing
*/
public function handleExport()
{
return $this->handle(
get_class($this)
);
}
/**
* Load the file
* @return \Maatwebsite\Excel\Readers\LaravelExcelReader
*/
public function createNewFile()
{
// Load the file
$file = $this->excel->create(
$this->getFilename()
);
return $file;
}
/**
* Dynamically call methods
* @param string $method
* @param array $params
* @return mixed
*/
public function __call($method, $params)
{
return call_user_func_array([$this->file, $method], $params);
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Filters;
use PHPExcel_Reader_IReadFilter;
class ChunkReadFilter implements PHPExcel_Reader_IReadFilter
{
/**
* Start row
* @var integer
*/
private $_startRow = 0;
/**
* End row
* @var integer
*/
private $_endRow = 0;
/**
* Set the list of rows that we want to read
* @param integer $startRow
* @param integer $chunkSize
* @return void
*/
public function setRows($startRow, $chunkSize)
{
$this->_startRow = $startRow;
$this->_endRow = $startRow + $chunkSize;
}
/**
* Read the cell
* @param string $column
* @param integer $row
* @param string $worksheetName
* @return booleaan
*/
public function readCell($column, $row, $worksheetName = '')
{
// Only read the heading row, and the rows that are configured in $this->_startRow and $this->_endRow
if (($row == config('excel.import.startRow')) || ($row >= $this->_startRow && $row <= $this->_endRow)) {
return true;
}
return false;
}
}
<?php namespace Maatwebsite\Excel\Parsers;
use DOMDocument;
use Illuminate\Support\Facades\URL;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
/**
*
* LaravelExcel CSS Parser
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class CssParser {
/**
* @var CssToInlineStyles
*/
protected $cssInliner;
/**
* DOM xml
* @var \SimpleXMLElement
*/
protected $xml;
/**
* Style sheet links
* @var array
*/
protected $links = array();
/**
* Construct the css parser
* @param CssToInlineStyles $cssInliner
*/
public function __construct(CssToInlineStyles $cssInliner)
{
$this->cssInliner = $cssInliner;
}
/**
* Transform the found css to inline styles
*/
public function transformCssToInlineStyles($html)
{
// Clean-up html
$this->cssInliner->setCleanup(true);
// Set html
$this->cssInliner->setHtml($html);
// Use inline style blocks
$this->cssInliner->setUseInlineStylesBlock(true);
// Loop through all stylesheets
foreach($this->links as $link)
{
$css = file_get_contents($link);
$this->cssInliner->setCSS($css);
}
return $this->cssInliner->convert();
}
/**
* Find the stylesheets inside the view
* @param DOMDocument $dom
* @return CssParser
*/
public function findStyleSheets(DOMDocument $dom)
{
// Import the dom
$this->importDom($dom);
// Get all stylesheet tags
$tags = $this->getStyleSheetTags();
foreach ($tags as $node)
{
$this->links[] = $this->getCleanStyleSheetLink($node);
}
// We don't need duplicate css files
$this->links = array_unique($this->links);
return $this;
}
/**
* Import the dom
* @return SimpleXMLElement
*/
protected function importDom(DOMDocument $dom)
{
return $this->xml = simplexml_import_dom($dom);
}
/**
* Get all stylesheet tags
* @return array
*/
protected function getStyleSheetTags()
{
return $this->xml->xpath('//link[@rel="stylesheet"]');
}
/**
* Get the clean link to the stylesheet
* @param string $node
* @return string
*/
protected function getCleanStyleSheetLink($node)
{
// Get the link
$link = $node->attributes()->href;
return $link;
}
/**
* Get css from link
* @param string $link
* @return string|boolean
*/
protected function getCssFromLink($link)
{
return file_get_contents($link);
}
}
<?php namespace Maatwebsite\Excel\Parsers;
use Maatwebsite\Excel\Readers\Html;
use Illuminate\Support\Facades\View;
/**
*
* LaravelExcel ViewParser
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class ViewParser {
/**
* View file
* @var string
*/
public $view;
/**
* Data array
* @var array
*/
public $data = array();
/**
* View merge data
* @var array
*/
public $mergeData = array();
/**
* Construct the view parser
* @param Html $reader
* @return \Maatwebsite\Excel\Parsers\ViewParser
*/
public function __construct(Html $reader)
{
$this->reader = $reader;
}
/**
* Parse the view
* @param \Maatwebsite\Excel\Classes\LaravelExcelWorksheet $sheet
* @return \Maatwebsite\Excel\Classes\LaravelExcelWorksheet
*/
public function parse($sheet)
{
$html = View::make($this->getView(), $this->getData(), $this->getMergeData())->render();
return $this->_loadHTML($sheet, $html);
}
/**
* Load the HTML
* @param \Maatwebsite\Excel\Classes\LaravelExcelWorksheet $sheet
* @param string $html
* @return \Maatwebsite\Excel\Classes\LaravelExcelWorksheet
*/
protected function _loadHTML($sheet, $html)
{
return $this->reader->load($html, true, $sheet);
}
/**
* Get the view
* @return string
*/
public function getView()
{
return $this->view;
}
/**
* Get data
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* Get merge data
* @return array
*/
public function getMergeData()
{
return $this->mergeData;
}
/**
* Set the view
* @param bool|string $view
*/
public function setView($view = false)
{
if ($view)
$this->view = $view;
}
/**
* Set the data
* @param array $data
*/
public function setData($data = array())
{
if (!empty($data))
$this->data = array_merge($this->data, $data);
}
/**
* Set the merge data
* @param array $mergeData
*/
public function setMergeData($mergeData = array())
{
if (!empty($mergeData))
$this->mergeData = array_merge($this->mergeData, $mergeData);
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Readers;
use Closure;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
/**
*
* LaravelExcel Batch Importer
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class Batch {
/**
* Excel object
* @var Excel
*/
protected $excel;
/**
* Batch files
* @var array
*/
public $files = array();
/**
* Set allowed file extensions
* @var array
*/
protected $allowedFileExtensions = array(
'xls',
'xlsx',
'csv'
);
/**
* Start the Batach
* @param Excel $excel
* @param array $files
* @param Closure $callback
* @return Excel
*/
public function start(Excel $excel, $files, Closure $callback)
{
// Set excel object
$this->excel = $excel;
// Set files
$this->_setFiles($files);
// Do the callback
if ($callback instanceof Closure)
{
foreach ($this->getFiles() as $file)
{
// Load the file
$excel = $this->excel->load($file);
// Do a callback with the loaded file
call_user_func($callback, $excel, $file);
}
}
// Return our excel object
return $this->excel;
}
/**
* Get the files
* @return array
*/
public function getFiles()
{
return $this->files;
}
/**
* Set the batch files
* @param array|string $files
* @throws LaravelExcelException
* @return void
*/
protected function _setFiles($files)
{
// If the param is an array, these will be the files for the batch import
if (is_array($files))
{
$this->files = $this->_getFilesByArray($files);
}
// Get all the files inside a folder
elseif (is_string($files))
{
$this->files = $this->_getFilesByFolder($files);
}
// Check if files were found
if (empty($this->files))
throw new LaravelExcelException('[ERROR]: No files were found. Batch terminated.');
}
/**
* Set files by array
* @param array $array
* @return array
*/
protected function _getFilesByArray($array)
{
$files = array();
// Make sure we have real paths
foreach ($array as $i => $file)
{
$files[$i] = realpath($file) ? $file : base_path($file);
}
return $files;
}
/**
* Get all files inside a folder
* @param string $folder
* @return array
*/
protected function _getFilesByFolder($folder)
{
// Check if it's a real path
if (!realpath($folder))
$folder = base_path($folder);
// Find path names matching our pattern of excel extensions
$glob = glob($folder . '/*.{' . implode(',', $this->allowedFileExtensions) . '}', GLOB_BRACE);
// If no matches, return empty array
if ($glob === false) return array();
// Return files
return array_filter($glob, function ($file)
{
return filetype($file) == 'file';
});
}
}
\ No newline at end of file
<?php
namespace Maatwebsite\Excel\Readers;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Filters\ChunkReadFilter;
use SuperClosure\Serializer;
class ChunkedReadJob implements SelfHandling, ShouldQueue
{
/**
* @var int
*/
private $startRow;
/**
* @var callable
*/
private $callback;
/**
* @var
*/
private $chunkSize;
/**
* @var
*/
private $startIndex;
/**
* @var
*/
private $file;
/**
* @var null
*/
private $sheets;
/**
* @var bool
*/
private $shouldQueue;
/**
* ChunkedReadJob constructor.
*
* @param $file
* @param null $sheets
* @param int $startRow
* @param $startIndex
* @param $chunkSize
* @param callable $callback
* @param bool $shouldQueue
*/
public function __construct(
$file,
$sheets = null,
$startRow,
$startIndex,
$chunkSize,
callable $callback,
$shouldQueue = true
) {
$this->startRow = $startRow;
$this->chunkSize = $chunkSize;
$this->startIndex = $startIndex;
$this->file = $file;
$this->callback = $shouldQueue ? (new Serializer)->serialize($callback) : $callback;
$this->sheets = $sheets;
$this->shouldQueue = $shouldQueue;
}
/***
* Handle the read job
*/
public function handle()
{
$reader = app('excel.reader');
$reader->injectExcel(app('phpexcel'));
$reader->_init($this->file);
$filter = new ChunkReadFilter();
$reader->reader->setLoadSheetsOnly($this->sheets);
$reader->reader->setReadFilter($filter);
$reader->reader->setReadDataOnly(true);
// Set the rows for the chunking
$filter->setRows($this->startRow, $this->chunkSize);
// Load file with chunk filter enabled
$reader->excel = $reader->reader->load($this->file);
// Slice the results
$results = $reader->get()->slice($this->startIndex, $this->chunkSize);
$callback = $this->shouldQueue ? (new Serializer)->unserialize($this->callback) : $this->callback;
// Do a callback
if (is_callable($callback)) {
$break = call_user_func($callback, $results);
}
$reader->_reset();
unset($reader, $results);
if ($break) {
return true;
}
}
}
<?php namespace Maatwebsite\Excel\Readers;
use Closure;
use PHPExcel;
use Maatwebsite\Excel\Excel;
use Illuminate\Support\Facades\Config;
use Maatwebsite\Excel\Collections\SheetCollection;
use Maatwebsite\Excel\Exceptions\LaravelExcelException;
/**
*
* LaravelExcel ConfigReader
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class ConfigReader {
/**
* Excel object
* @var PHPExcel
*/
public $excel;
/**
* The sheet
* @var LaravelExcelWorksheet
*/
public $sheet;
/**
* The sheetname
* @var string
*/
public $sheetName;
/**
* Collection of sheets (through the config reader)
* @var SheetCollection
*/
public $sheetCollection;
/**
* Constructor
* @param PHPExcel $excel
* @param string $config
* @param callback $callback
*/
public function __construct(PHPExcel $excel, $config = 'excel.import', $callback = null)
{
// Set excel object
$this->excel = $excel;
// config name
$this->configName = $config;
// start
$this->start($callback);
}
/**
* Start the import
* @param bool|callable $callback $callback
* @throws \PHPExcel_Exception
* @return void
*/
public function start($callback = false)
{
// Init a new sheet collection
$this->sheetCollection = new SheetCollection();
// Get the sheet names
if ($sheets = $this->excel->getSheetNames())
{
// Loop through the sheets
foreach ($sheets as $index => $name)
{
// Set sheet name
$this->sheetName = $name;
// Set sheet
$this->sheet = $this->excel->setActiveSheetIndex($index);
// Do the callback
if ($callback instanceof Closure)
{
call_user_func($callback, $this);
}
// If no callback, put it inside the sheet collection
else
{
$this->sheetCollection->push(clone $this);
}
}
}
}
/**
* Get the sheet collection
* @return SheetCollection
*/
public function getSheetCollection()
{
return $this->sheetCollection;
}
/**
* Get value by index
* @param string $field
* @return string|null
*/
protected function valueByIndex($field)
{
// Convert field name
$field = snake_case($field);
// Get coordinate
if ($coordinate = $this->getCoordinateByKey($field))
{
// return cell value by coordinate
return $this->getCellValueByCoordinate($coordinate);
}
return null;
}
/**
* Return cell value
* @param string $coordinate
* @return string|null
*/
protected function getCellValueByCoordinate($coordinate)
{
if ($this->sheet)
{
if (str_contains($coordinate, ':'))
{
// We want to get a range of cells
$values = $this->sheet->rangeToArray($coordinate);
return $values;
}
else
{
// We want 1 specific cell
return $this->sheet->getCell($coordinate)->getValue();
}
}
return null;
}
/**
* Get the coordinates from the config file
* @param string $field
* @return string|boolean
*/
protected function getCoordinateByKey($field)
{
return Config::get($this->configName . '.' . $this->sheetName . '.' . $field, false);
}
/**
* Dynamically get a value by config
* @param string $field
* @return string
*/
public function __get($field)
{
return $this->valueByIndex($field);
}
}
\ No newline at end of file
<?php namespace Maatwebsite\Excel\Writers;
use Maatwebsite\Excel\Classes\LaravelExcelWorksheet;
/**
*
* LaravelExcel Excel writer
*
* @category Laravel Excel
* @version 1.0.0
* @package maatwebsite/excel
* @copyright Copyright (c) 2013 - 2014 Maatwebsite (http://www.maatwebsite.nl)
* @author Maatwebsite <info@maatwebsite.nl>
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
*/
class CellWriter {
/**
* Current $sheet
* @var LaravelExcelWorksheet
*/
public $sheet;
/**
* Selected cells
* @var array
*/
public $cells;
/**
* Constructor
* @param array $cells
* @param LaravelExcelWorksheet $sheet
*/
public function __construct($cells, LaravelExcelWorksheet $sheet)
{
$this->cells = $cells;
$this->sheet = $sheet;
}
/**
* Set cell value
* @param [type] $value
* @return CellWriter
*/
public function setValue($value)
{
// Only set cell value for single cells
if (!str_contains($this->cells, ':'))
{
$this->sheet->setCellValue($this->cells, $value);
}
return $this;
}
/**
* Set the background
* @param string $color
* @param string $type
* @param string $colorType
* @return CellWriter
*/
public function setBackground($color, $type = 'solid', $colorType = 'rgb')
{
return $this->setColorStyle('fill', $color, $type, $colorType);
}
/**
* Set the font color
* @param string $color
* @param string $colorType
* @return CellWriter
*/
public function setFontColor($color, $colorType = 'rgb')
{
return $this->setColorStyle('font', $color, false, $colorType);
}
/**
* Set the font
* @param $styles
* @return CellWriter
*/
public function setFont($styles)
{
return $this->setStyle('font', $styles);
}
/**
* Set font family
* @param string $family
* @return CellWriter
*/
public function setFontFamily($family)
{
return $this->setStyle('font', array(
'name' => $family
));
}
/**
* Set font size
* @param string $size
* @return CellWriter
*/
public function setFontSize($size)
{
return $this->setStyle('font', array(
'size' => $size
));
}
/**
* Set font weight
* @param boolean|string $bold
* @return CellWriter
*/
public function setFontWeight($bold = true)
{
return $this->setStyle('font', array(
'bold' => ($bold == 'bold' || $bold) ? true : false
));
}
/**
* Set border
* @param string $top
* @param bool|string $right
* @param bool|string $bottom
* @param bool|string $left
* @return CellWriter
*/
public function setBorder($top = 'none', $right = 'none', $bottom = 'none', $left = 'none')
{
// Set the border styles
$styles = is_array($top) ? $top : array(
'top' => array(
'style' => $top
),
'left' => array(
'style' => $left,
),
'right' => array(
'style' => $right,
),
'bottom' => array(
'style' => $bottom,
)
);
return $this->setStyle('borders', $styles);
}
/**
* Set the text rotation
* @param integer $alignment
* @return CellWriter
*/
public function setTextRotation($degrees)
{
$style = $this->getCellStyle()->getAlignment()->setTextRotation($degrees);
return $this;
}
/**
* Set the alignment
* @param string $alignment
* @return CellWriter
*/
public function setAlignment($alignment)
{
return $this->setStyle('alignment', array(
'horizontal' => $alignment
));
}
/**
* Set vertical alignment
* @param string $alignment
* @return CellWriter
*/
public function setValignment($alignment)
{
return $this->setStyle('alignment', array(
'vertical' => $alignment
));
}
/**
* Set the color style
* @param $styleType
* @param string $color
* @param boolean $type
* @param string $colorType
* @return CellWriter
*/
protected function setColorStyle($styleType, $color, $type = false, $colorType = 'rgb')
{
// Set the styles
$styles = is_array($color) ? $color : array(
'type' => $type,
'color' => array($colorType => str_replace('#', '', $color))
);
return $this->setStyle($styleType, $styles);
}
/**
* Set style
* @param $styleType
* @param string $styles
* @return CellWriter
*/
protected function setStyle($styleType, $styles)
{
// Get the cell style
$style = $this->getCellStyle();
// Apply style from array
$style->applyFromArray(array(
$styleType => $styles
));
return $this;
}
/**
* Get the cell style
* @return \PHPExcel_Style
*/
protected function getCellStyle()
{
return $this->sheet->getStyle($this->cells);
}
}
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment