diff --git a/docs/faq.md b/docs/faq.md index d10c0c2e..abd5313c 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -1,20 +1,27 @@ # Frequently asked questions -The up-to-date F.A.Q. page for PHPExcel can be found on [http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements](http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements). +The up-to-date F.A.Q. page for PHPExcel can be found on +. ## There seems to be a problem with character encoding... -It is necessary to use UTF-8 encoding for all texts in PhpSpreadsheet. If the script uses different encoding then you can convert those texts with PHP's iconv() or mb_convert_encoding() functions. +It is necessary to use UTF-8 encoding for all texts in PhpSpreadsheet. +If the script uses different encoding then you can convert those texts +with PHP's iconv() or mb\_convert\_encoding() functions. ## PHP complains about ZipArchive not being found -Make sure you meet all requirements, especially php_zip extension should be enabled. +Make sure you meet all requirements, especially php\_zip extension +should be enabled. -The ZipArchive class is only required when reading or writing formats that use Zip compression (Xlsx and Ods). Since version 1.7.6 the PCLZip library has been bundled with PhpSpreadsheet as an alternative to the ZipArchive class. +The ZipArchive class is only required when reading or writing formats +that use Zip compression (Xlsx and Ods). Since version 1.7.6 the PCLZip +library has been bundled with PhpSpreadsheet as an alternative to the +ZipArchive class. This can be enabled by calling: -```php +``` php \PhpOffice\PhpSpreadsheet\Settings::setZipClass(\PhpOffice\PhpSpreadsheet\Settings::PCLZIP); ``` @@ -22,73 +29,120 @@ This can be enabled by calling: You can revert to using ZipArchive by calling: -```php +``` php \PhpOffice\PhpSpreadsheet\Settings::setZipClass(\PhpOffice\PhpSpreadsheet\Settings::ZIPARCHIVE); ``` -At present, this only allows you to write Xlsx files without the need for ZipArchive (not to read Xlsx or Ods) +At present, this only allows you to write Xlsx files without the need +for ZipArchive (not to read Xlsx or Ods) ## Excel 2007 cannot open the file generated on Windows -"Excel found unreadable content in '*.xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes." +"Excel found unreadable content in '\*.xlsx'. Do you want to recover the +contents of this workbook? If you trust the source of this workbook, +click Yes." -Some older versions of the 5.2.x php_zip extension on Windows contain an error when creating ZIP files. The version that can be found on [http://snaps.php.net/win32/php5.2-win32-latest.zip](http://snaps.php.net/win32/php5.2-win32-latest.zip) should work at all times. +Some older versions of the 5.2.x php\_zip extension on Windows contain +an error when creating ZIP files. The version that can be found on + should work at all +times. Alternatively, upgrading to at least PHP 5.2.9 should solve the problem. -If you can't locate a clean copy of ZipArchive, then you can use the PCLZip library as an alternative when writing Xlsx files, as described above. +If you can't locate a clean copy of ZipArchive, then you can use the +PCLZip library as an alternative when writing Xlsx files, as described +above. ## Fatal error: Allowed memory size of xxx bytes exhausted (tried to allocate yyy bytes) in zzz on line aaa -PhpSpreadsheet holds an "in memory" representation of a spreadsheet, so it is susceptible to PHP's memory limitations. The memory made available to PHP can be increased by editing the value of the memory_limit directive in your php.ini file, or by using ini_set('memory_limit', '128M') within your code (ISP permitting). +PhpSpreadsheet holds an "in memory" representation of a spreadsheet, so +it is susceptible to PHP's memory limitations. The memory made available +to PHP can be increased by editing the value of the memory\_limit +directive in your php.ini file, or by using ini\_set('memory\_limit', +'128M') within your code (ISP permitting). -Some Readers and Writers are faster than others, and they also use differing amounts of memory. You can find some indication of the relative performance and memory usage for the different Readers and Writers, over the different versions of PhpSpreadsheet, on the [discussion board](http://phpexcel.codeplex.com/Thread/View.aspx?ThreadId=234150). +Some Readers and Writers are faster than others, and they also use +differing amounts of memory. You can find some indication of the +relative performance and memory usage for the different Readers and +Writers, over the different versions of PhpSpreadsheet, on the +[discussion +board](http://phpexcel.codeplex.com/Thread/View.aspx?ThreadId=234150). -If you've already increased memory to a maximum, or can't change your memory limit, then [this discussion](http://phpexcel.codeplex.com/Thread/View.aspx?ThreadId=242712) on the board describes some of the methods that can be applied to reduce the memory usage of your scripts using PhpSpreadsheet. +If you've already increased memory to a maximum, or can't change your +memory limit, then [this +discussion](http://phpexcel.codeplex.com/Thread/View.aspx?ThreadId=242712) +on the board describes some of the methods that can be applied to reduce +the memory usage of your scripts using PhpSpreadsheet. ## Protection on my worksheet is not working? -When you make use of any of the worksheet protection features (e.g. cell range protection, prohibiting deleting rows, ...), make sure you enable worksheet security. This can for example be done like this: +When you make use of any of the worksheet protection features (e.g. cell +range protection, prohibiting deleting rows, ...), make sure you enable +worksheet security. This can for example be done like this: -```php +``` php $spreadsheet->getActiveSheet()->getProtection()->setSheet(true); ``` -## Feature X is not working with Reader_Y / Writer_Z +## Feature X is not working with Reader\_Y / Writer\_Z -Not all features of PhpSpreadsheet are implemented in all of the Reader / Writer classes. This is mostly due to underlying libraries not supporting a specific feature or not having implemented a specific feature. +Not all features of PhpSpreadsheet are implemented in all of the Reader +/ Writer classes. This is mostly due to underlying libraries not +supporting a specific feature or not having implemented a specific +feature. -For example autofilter is not implemented in PEAR Spreadsheet_Excel_writer, which is the base of our Xls writer. +For example autofilter is not implemented in PEAR +Spreadsheet\_Excel\_writer, which is the base of our Xls writer. -We are slowly building up a list of features, together with the different readers and writers that support them, in the "Functionality Cross-Reference.xls" file in the /Documentation folder. +We are slowly building up a list of features, together with the +different readers and writers that support them, in the "Functionality +Cross-Reference.xls" file in the /Documentation folder. ## Formulas don't seem to be calculated in Excel2003 using compatibility pack? -This is normal behaviour of the compatibility pack, Xlsx displays this correctly. Use \PhpOffice\PhpSpreadsheet\Writer\Xls if you really need calculated values, or force recalculation in Excel2003. +This is normal behaviour of the compatibility pack, Xlsx displays this +correctly. Use \PhpOffice\PhpSpreadsheet\Writer\Xls if you really need +calculated values, or force recalculation in Excel2003. ## Setting column width is not 100% accurate -Trying to set column width, I experience one problem. When I open the file in Excel, the actual width is 0.71 less than it should be. +Trying to set column width, I experience one problem. When I open the +file in Excel, the actual width is 0.71 less than it should be. -The short answer is that PhpSpreadsheet uses a measure where padding is included. See section: "Setting a column's width" for more details. +The short answer is that PhpSpreadsheet uses a measure where padding is +included. See section: "Setting a column's width" for more details. ## How do I use PhpSpreadsheet with my framework - - There are some instructions for using PhpSpreadsheet with Joomla on the [Joomla message board](http://http:/forum.joomla.org/viewtopic.php?f=304&t=433060) - - A page of advice on using [PhpSpreadsheet in the Yii framework](http://www.yiiframework.com/wiki/101/how-to-use-phpexcel-external-library-with-yii/) - - [The Bakery](http://bakery.cakephp.org/articles/melgior/2010/01/26/simple-excel-spreadsheet-helper) has some helper classes for reading and writing with PhpSpreadsheet within CakePHP - - Integrating [PhpSpreadsheet into Kohana 3](http://www.flynsarmy.com/2010/07/phpexcel-module-for-kohana-3/) and [Интеграция PHPExcel и Kohana Framework][http://szpargalki.blogspot.com/2011/02/phpexcel-kohana-framework.html] - - Using [PhpSpreadsheet with TYPO3](http://typo3.org/documentation/document-library/extension-manuals/phpexcel_library/1.1.1/view/toc/0/) +- There are some instructions for using PhpSpreadsheet with Joomla on + the [Joomla message + board](http://http:/forum.joomla.org/viewtopic.php?f=304&t=433060) +- A page of advice on using [PhpSpreadsheet in the Yii + framework](http://www.yiiframework.com/wiki/101/how-to-use-phpexcel-external-library-with-yii/) +- [The + Bakery](http://bakery.cakephp.org/articles/melgior/2010/01/26/simple-excel-spreadsheet-helper) + has some helper classes for reading and writing with PhpSpreadsheet + within CakePHP +- Integrating [PhpSpreadsheet into Kohana + 3](http://www.flynsarmy.com/2010/07/phpexcel-module-for-kohana-3/) + and \[Интеграция PHPExcel и Kohana + Framework\]\[http://szpargalki.blogspot.com/2011/02/phpexcel-kohana-framework.html\] +- Using [PhpSpreadsheet with + TYPO3](http://typo3.org/documentation/document-library/extension-manuals/phpexcel_library/1.1.1/view/toc/0/) ## Joomla Autoloader interferes with PhpSpreadsheet Autoloader -Thanks to peterrlynch for the following advice on resolving issues between the [PhpSpreadsheet autoloader and Joomla Autoloader](http://phpexcel.codeplex.com/discussions/211925) - +Thanks to peterrlynch for the following advice on resolving issues +between the [PhpSpreadsheet autoloader and Joomla +Autoloader](http://phpexcel.codeplex.com/discussions/211925) ### Tutorials - - [English PHPExcel tutorial](http://openxmldeveloper.org) - - [French PHPExcel tutorial](http://g-ernaelsten.developpez.com/tutoriels/excel2007/) - - [Russian PHPExcel Blog Postings](http://www.web-junior.net/sozdanie-excel-fajjlov-s-pomoshhyu-phpexcel/) - - [A Japanese-language introduction to PHPExcel](http://journal.mycom.co.jp/articles/2009/03/06/phpexcel/index.html) +- [English PHPExcel tutorial](http://openxmldeveloper.org) +- [French PHPExcel + tutorial](http://g-ernaelsten.developpez.com/tutoriels/excel2007/) +- [Russian PHPExcel Blog + Postings](http://www.web-junior.net/sozdanie-excel-fajjlov-s-pomoshhyu-phpexcel/) +- [A Japanese-language introduction to + PHPExcel](http://journal.mycom.co.jp/articles/2009/03/06/phpexcel/index.html) diff --git a/docs/index.md b/docs/index.md index 520b0e25..724f172d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,10 +1,10 @@ -Welcome to PhpSpreadsheet's documentation -========================================== +# Welcome to PhpSpreadsheet's documentation ![Logo](./assets/logo.svg) - -PhpSpreadsheet is a library written in pure PHP and providing a set of classes that allow you to read from and to write to different spreadsheet file formats, like Excel and LibreOffice Calc. +PhpSpreadsheet is a library written in pure PHP and providing a set of +classes that allow you to read from and to write to different +spreadsheet file formats, like Excel and LibreOffice Calc. # Getting started @@ -12,30 +12,33 @@ PhpSpreadsheet is a library written in pure PHP and providing a set of classes t The following software is required to develop using PhpSpreadsheet: - - PHP version 5.5 or newer - - PHP extension php_zip enabled (see [FAQ](./faq.md#php-complains-about-ziparchive-not-being-found)) - - PHP extension php_xml enabled - - PHP extension php_gd2 enabled (if not compiled in) - +- PHP version 5.5 or newer +- PHP extension php\_zip enabled (see + [FAQ](./faq.md#php-complains-about-ziparchive-not-being-found)) +- PHP extension php\_xml enabled +- PHP extension php\_gd2 enabled (if not compiled in) ## Installation instructions -Installation is quite easy: copy the contents of the Classes folder to any location within your application source directories. +Installation is quite easy: copy the contents of the Classes folder to +any location within your application source directories. *Example:* -If your web root folder is /var/www/ you may want to create a subfolder called /var/www/Classes/ and copy the files into that folder so you end up with files: +If your web root folder is /var/www/ you may want to create a subfolder +called /var/www/Classes/ and copy the files into that folder so you end +up with files: /var/www/Classes/PHPExcel.php /var/www/Classes/PHPExcel/Calculation.php /var/www/Classes/PHPExcel/Cell.php ... - ## Getting started -A good way to get started is to run some of the tests included in the download. -Copy the "Examples" folder next to your "Classes" folder from above so you end up with: +A good way to get started is to run some of the tests included in the +download. Copy the "Examples" folder next to your "Classes" folder from +above so you end up with: /var/www/Examples/01simple.php /var/www/Examples/02types.php @@ -44,22 +47,27 @@ Copy the "Examples" folder next to your "Classes" folder from above so you end u Start running the tests by pointing your browser to the test scripts: http://example.com/Tests/01simple.php -http://example.com/Tests/02types.php -... - -**Note:** It may be necessary to modify the include/require statements at the beginning of each of the test scripts if your "Classes" folder from above is named differently. +http://example.com/Tests/02types.php ... +**Note:** It may be necessary to modify the include/require statements +at the beginning of each of the test scripts if your "Classes" folder +from above is named differently. ## Useful links and tools -There are some links and tools which are very useful when developing using PhpSpreadsheet. +There are some links and tools which are very useful when developing +using PhpSpreadsheet. ### OpenXML / SpreadsheetML - - [File format documentation](http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm) - - [OpenXML Explained e-book](http://openxmldeveloper.org/articles/1970.aspx) - - [Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 File Formats](http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en) - - [OpenXML Package Explorer](http://www.codeplex.com/PackageExplorer/) +- [File format + documentation](http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm) +- [OpenXML Explained + e-book](http://openxmldeveloper.org/articles/1970.aspx) +- [Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint + 2007 File + Formats](http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en) +- [OpenXML Package Explorer](http://www.codeplex.com/PackageExplorer/) # Architecture @@ -67,48 +75,74 @@ There are some links and tools which are very useful when developing using PhpSp ![01-schematic.png](./images/01-schematic.png "Basic Architecture Schematic") - ## Lazy Loader -PhpSpreadsheet implements an autoloader or "lazy loader", which means that it is not necessary to include every file within PhpSpreadsheet. It is only necessary to include the initial PhpSpreadsheet class file, then the autoloader will include other class files as and when required, so only those files that are actually required by your script will be loaded into PHP memory. The main benefit of this is that it reduces the memory footprint of PhpSpreadsheet itself, so that it uses less PHP memory. +PhpSpreadsheet implements an autoloader or "lazy loader", which means +that it is not necessary to include every file within PhpSpreadsheet. It +is only necessary to include the initial PhpSpreadsheet class file, then +the autoloader will include other class files as and when required, so +only those files that are actually required by your script will be +loaded into PHP memory. The main benefit of this is that it reduces the +memory footprint of PhpSpreadsheet itself, so that it uses less PHP +memory. -If your own scripts already define an autoload function, then this may be overwritten by the PhpSpreadsheet autoload function. For example, if you have: -```php +If your own scripts already define an autoload function, then this may +be overwritten by the PhpSpreadsheet autoload function. For example, if +you have: + +``` php function __autoload($class) { ... } ``` + Do this instead: -```php + +``` php function myAutoload($class) { ... } spl_autoload_register('myAutoload'); ``` -Your autoloader will then co-exist with the autoloader of PhpSpreadsheet. +Your autoloader will then co-exist with the autoloader of +PhpSpreadsheet. ## Spreadsheet in memory -PhpSpreadsheet's architecture is built in a way that it can serve as an in-memory spreadsheet. This means that, if one would want to create a web based view of a spreadsheet which communicates with PhpSpreadsheet's object model, he would only have to write the front-end code. - -Just like desktop spreadsheet software, PhpSpreadsheet represents a spreadsheet containing one or more worksheets, which contain cells with data, formulas, images, ... +PhpSpreadsheet's architecture is built in a way that it can serve as an +in-memory spreadsheet. This means that, if one would want to create a +web based view of a spreadsheet which communicates with PhpSpreadsheet's +object model, he would only have to write the front-end code. +Just like desktop spreadsheet software, PhpSpreadsheet represents a +spreadsheet containing one or more worksheets, which contain cells with +data, formulas, images, ... ## Readers and writers -On its own, the `Spreadsheet` class does not provide the functionality to read from or write to a persisted spreadsheet (on disk or in a database). To provide that functionality, readers and writers can be used. +On its own, the `Spreadsheet` class does not provide the functionality +to read from or write to a persisted spreadsheet (on disk or in a +database). To provide that functionality, readers and writers can be +used. -By default, the PhpSpreadsheet package provides some readers and writers, including one for the Open XML spreadsheet format (a.k.a. Excel 2007 file format). You are not limited to the default readers and writers, as you are free to implement the \PhpOffice\PhpSpreadsheet\Reader\IReader and \PhpOffice\PhpSpreadsheet\Writer\IWriter interface in a custom class. +By default, the PhpSpreadsheet package provides some readers and +writers, including one for the Open XML spreadsheet format (a.k.a. Excel +2007 file format). You are not limited to the default readers and +writers, as you are free to implement the +\PhpOffice\PhpSpreadsheet\Reader\IReader and +\PhpOffice\PhpSpreadsheet\Writer\IWriter interface in a custom class. ![02-readers-writers.png](./images/02-readers-writers.png "Readers/Writers") ## Fluent interfaces -PhpSpreadsheet supports fluent interfaces in most locations. This means that you can easily "chain" calls to specific methods without requiring a new PHP statement. For example, take the following code: +PhpSpreadsheet supports fluent interfaces in most locations. This means +that you can easily "chain" calls to specific methods without requiring +a new PHP statement. For example, take the following code: -```php +``` php $spreadsheet->getProperties()->setCreator("Maarten Balliauw"); $spreadsheet->getProperties()->setLastModifiedBy("Maarten Balliauw"); $spreadsheet->getProperties()->setTitle("Office 2007 XLSX Test Document"); @@ -120,7 +154,7 @@ $spreadsheet->getProperties()->setCategory("Test result file"); This can be rewritten as: -```php +``` php $spreadsheet->getProperties() ->setCreator("Maarten Balliauw") ->setLastModifiedBy("Maarten Balliauw") @@ -131,25 +165,37 @@ $spreadsheet->getProperties() ->setCategory("Test result file"); ``` - > __Using fluent interfaces is not required__ - > Fluent interfaces have been implemented to provide a convenient programming API. Use of them is not required, but can make your code easier to read and maintain. - > It can also improve performance, as you are reducing the overall number of calls to PhpSpreadsheet methods: in the above example, the `getProperties()` method is being called only once rather than 7 times in the non-fluent version. +> **Using fluent interfaces is not required** Fluent interfaces have +> been implemented to provide a convenient programming API. Use of them +> is not required, but can make your code easier to read and maintain. +> It can also improve performance, as you are reducing the overall +> number of calls to PhpSpreadsheet methods: in the above example, the +> `getProperties()` method is being called only once rather than 7 times +> in the non-fluent version. # Creating a spreadsheet ## The `Spreadsheet` class -The `Spreadsheet` class is the core of PhpSpreadsheet. It contains references to the contained worksheets, document security settings and document meta data. +The `Spreadsheet` class is the core of PhpSpreadsheet. It contains +references to the contained worksheets, document security settings and +document meta data. -To simplify the PhpSpreadsheet concept: the `Spreadsheet` class represents your workbook. +To simplify the PhpSpreadsheet concept: the `Spreadsheet` class +represents your workbook. -Typically, you will create a workbook in one of two ways, either by loading it from a spreadsheet file, or creating it manually. A third option, though less commonly used, is cloning an existing workbook that has been created using one of the previous two methods. +Typically, you will create a workbook in one of two ways, either by +loading it from a spreadsheet file, or creating it manually. A third +option, though less commonly used, is cloning an existing workbook that +has been created using one of the previous two methods. ### Loading a Workbook from a file -Details of the different spreadsheet formats supported, and the options available to read them into a Spreadsheet object are described fully in the [Reading Files](../topics/reading-files.md) document. +Details of the different spreadsheet formats supported, and the options +available to read them into a Spreadsheet object are described fully in +the [Reading Files](../topics/reading-files.md) document. -```php +``` php $inputFileName = './sampleData/example1.xls'; /** Load $inputFileName to a Spreadsheet object **/ @@ -158,9 +204,10 @@ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName); ### Creating a new workbook -If you want to create a new workbook, rather than load one from file, then you simply need to instantiate it as a new Spreadsheet object. +If you want to create a new workbook, rather than load one from file, +then you simply need to instantiate it as a new Spreadsheet object. -```php +``` php /** Create a new Spreadsheet Object **/ $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); ``` @@ -169,66 +216,104 @@ A new workbook will always be created with a single worksheet. ## Clearing a Workbook from memory -The PhpSpreadsheet object contains cyclic references (e.g. the workbook is linked to the worksheets, and the worksheets are linked to their parent workbook) which cause problems when PHP tries to clear the objects from memory when they are unset(), or at the end of a function when they are in local scope. The result of this is "memory leaks", which can easily use a large amount of PHP's limited memory. +The PhpSpreadsheet object contains cyclic references (e.g. the workbook +is linked to the worksheets, and the worksheets are linked to their +parent workbook) which cause problems when PHP tries to clear the +objects from memory when they are unset(), or at the end of a function +when they are in local scope. The result of this is "memory leaks", +which can easily use a large amount of PHP's limited memory. -This can only be resolved manually: if you need to unset a workbook, then you also need to "break" these cyclic references before doing so. PhpSpreadsheet provides the disconnectWorksheets() method for this purpose. +This can only be resolved manually: if you need to unset a workbook, +then you also need to "break" these cyclic references before doing so. +PhpSpreadsheet provides the disconnectWorksheets() method for this +purpose. -```php +``` php $spreadsheet->disconnectWorksheets(); unset($spreadsheet); ``` # Worksheets -A worksheet is a collection of cells, formulae, images, graphs, etc. It holds all data necessary to represent a spreadsheet worksheet. +A worksheet is a collection of cells, formulae, images, graphs, etc. It +holds all data necessary to represent a spreadsheet worksheet. -When you load a workbook from a spreadsheet file, it will be loaded with all its existing worksheets (unless you specified that only certain sheets should be loaded). When you load from non-spreadsheet files (such as a CSV or HTML file) or from spreadsheet formats that don't identify worksheets by name (such as SYLK), then a single worksheet called "WorkSheet1" will be created containing the data from that file. +When you load a workbook from a spreadsheet file, it will be loaded with +all its existing worksheets (unless you specified that only certain +sheets should be loaded). When you load from non-spreadsheet files (such +as a CSV or HTML file) or from spreadsheet formats that don't identify +worksheets by name (such as SYLK), then a single worksheet called +"WorkSheet1" will be created containing the data from that file. -When you instantiate a new workbook, PhpSpreadsheet will create it with a single worksheet called "WorkSheet1". +When you instantiate a new workbook, PhpSpreadsheet will create it with +a single worksheet called "WorkSheet1". -The `getSheetCount()` method will tell you the number of worksheets in the workbook; while the `getSheetNames()` method will return a list of all worksheets in the workbook, indexed by the order in which their "tabs" would appear when opened in MS Excel (or other appropriate Spreadsheet program). +The `getSheetCount()` method will tell you the number of worksheets in +the workbook; while the `getSheetNames()` method will return a list of +all worksheets in the workbook, indexed by the order in which their +"tabs" would appear when opened in MS Excel (or other appropriate +Spreadsheet program). -Individual worksheets can be accessed by name, or by their index position in the workbook. The index position represents the order that each worksheet "tab" is shown when the workbook is opened in MS Excel (or other appropriate Spreadsheet program). To access a sheet by its index, use the `getSheet()` method. +Individual worksheets can be accessed by name, or by their index +position in the workbook. The index position represents the order that +each worksheet "tab" is shown when the workbook is opened in MS Excel +(or other appropriate Spreadsheet program). To access a sheet by its +index, use the `getSheet()` method. -```php +``` php // Get the second sheet in the workbook // Note that sheets are indexed from 0 $spreadsheet->getSheet(1); ``` -If you don't specify a sheet index, then the first worksheet will be returned. +If you don't specify a sheet index, then the first worksheet will be +returned. -Methods also exist allowing you to reorder the worksheets in the workbook. +Methods also exist allowing you to reorder the worksheets in the +workbook. -To access a sheet by name, use the `getSheetByName()` method, specifying the name of the worksheet that you want to access. +To access a sheet by name, use the `getSheetByName()` method, specifying +the name of the worksheet that you want to access. -```php +``` php // Retrieve the worksheet called 'Worksheet 1' $spreadsheet->getSheetByName('Worksheet 1'); ``` -Alternatively, one worksheet is always the currently active worksheet, and you can access that directly. The currently active worksheet is the one that will be active when the workbook is opened in MS Excel (or other appropriate Spreadsheet program). +Alternatively, one worksheet is always the currently active worksheet, +and you can access that directly. The currently active worksheet is the +one that will be active when the workbook is opened in MS Excel (or +other appropriate Spreadsheet program). -```php +``` php // Retrieve the current active worksheet $spreadsheet->getActiveSheet(); ``` -You can change the currently active sheet by index or by name using the `setActiveSheetIndex()` and `setActiveSheetIndexByName()` methods. +You can change the currently active sheet by index or by name using the +`setActiveSheetIndex()` and `setActiveSheetIndexByName()` methods. ## Adding a new Worksheet -You can add a new worksheet to the workbook using the `createSheet()` method of the `Spreadsheet` object. By default, this will be created as a new "last" sheet; but you can also specify an index position as an argument, and the worksheet will be inserted at that position, shuffling all subsequent worksheets in the collection down a place. +You can add a new worksheet to the workbook using the `createSheet()` +method of the `Spreadsheet` object. By default, this will be created as +a new "last" sheet; but you can also specify an index position as an +argument, and the worksheet will be inserted at that position, shuffling +all subsequent worksheets in the collection down a place. -```php +``` php $spreadsheet->createSheet(); ``` -A new worksheet created using this method will be called "Worksheet\" where "\" is the lowest number possible to guarantee that the title is unique. +A new worksheet created using this method will be called +"Worksheet<n>" where "<n>" is the lowest number possible to +guarantee that the title is unique. -Alternatively, you can instantiate a new worksheet (setting the title to whatever you choose) and then insert it into your workbook using the addSheet() method. +Alternatively, you can instantiate a new worksheet (setting the title to +whatever you choose) and then insert it into your workbook using the +addSheet() method. -```php +``` php // Create a new worksheet called "My Data" $myWorkSheet = new \PhpOffice\PhpSpreadsheet\Worksheet($spreadsheet, 'My Data'); @@ -236,49 +321,60 @@ $myWorkSheet = new \PhpOffice\PhpSpreadsheet\Worksheet($spreadsheet, 'My Data'); $spreadsheet->addSheet($myWorkSheet, 0); ``` -If you don't specify an index position as the second argument, then the new worksheet will be added after the last existing worksheet. +If you don't specify an index position as the second argument, then the +new worksheet will be added after the last existing worksheet. ## Copying Worksheets -Sheets within the same workbook can be copied by creating a clone of the worksheet you wish to copy, and then using the addSheet() method to insert the clone into the workbook. +Sheets within the same workbook can be copied by creating a clone of the +worksheet you wish to copy, and then using the addSheet() method to +insert the clone into the workbook. -```php +``` php $clonedWorksheet = clone $spreadsheet->getSheetByName('Worksheet 1'); $clonedWorksheet->setTitle('Copy of Worksheet 1') $spreadsheet->addSheet($clonedWorksheet); ``` -You can also copy worksheets from one workbook to another, though this is more complex as PhpSpreadsheet also has to replicate the styling between the two workbooks. The addExternalSheet() method is provided for this purpose. +You can also copy worksheets from one workbook to another, though this +is more complex as PhpSpreadsheet also has to replicate the styling +between the two workbooks. The addExternalSheet() method is provided for +this purpose. -``` -$clonedWorksheet = clone $spreadsheet1->getSheetByName('Worksheet 1'); -$spreadsheet->addExternalSheet($clonedWorksheet); -``` + $clonedWorksheet = clone $spreadsheet1->getSheetByName('Worksheet 1'); + $spreadsheet->addExternalSheet($clonedWorksheet); -In both cases, it is the developer's responsibility to ensure that worksheet names are not duplicated. PhpSpreadsheet will throw an exception if you attempt to copy worksheets that will result in a duplicate name. +In both cases, it is the developer's responsibility to ensure that +worksheet names are not duplicated. PhpSpreadsheet will throw an +exception if you attempt to copy worksheets that will result in a +duplicate name. ## Removing a Worksheet -You can delete a worksheet from a workbook, identified by its index position, using the removeSheetByIndex() method +You can delete a worksheet from a workbook, identified by its index +position, using the removeSheetByIndex() method -```php +``` php $sheetIndex = $spreadsheet->getIndex( $spreadsheet->getSheetByName('Worksheet 1') ); $spreadsheet->removeSheetByIndex($sheetIndex); ``` -If the currently active worksheet is deleted, then the sheet at the previous index position will become the currently active sheet. +If the currently active worksheet is deleted, then the sheet at the +previous index position will become the currently active sheet. # Accessing cells -Accessing cells in a Spreadsheet should be pretty straightforward. This topic lists some of the options to access a cell. +Accessing cells in a Spreadsheet should be pretty straightforward. This +topic lists some of the options to access a cell. ## Setting a cell value by coordinate -Setting a cell value by coordinate can be done using the worksheet's `setCellValue()` method. +Setting a cell value by coordinate can be done using the worksheet's +`setCellValue()` method. -```php +``` php // Set cell A1 with a string value $spreadsheet->getActiveSheet()->setCellValue('A1', 'PhpSpreadsheet'); @@ -295,9 +391,10 @@ $spreadsheet->getActiveSheet()->setCellValue( ); ``` -Alternatively, you can retrieve the cell object, and then call the cell’s setValue() method: +Alternatively, you can retrieve the cell object, and then call the +cell’s setValue() method: -```php +``` php $spreadsheet->getActiveSheet() ->getCell('B8') ->setValue('Some value'); @@ -305,34 +402,53 @@ $spreadsheet->getActiveSheet() **Excel DataTypes** -MS Excel supports 7 basic datatypes - - string - - number - - boolean - - null - - formula - - error - - Inline (or rich text) string +MS Excel supports 7 basic datatypes - string - number - boolean - null - +formula - error - Inline (or rich text) string -By default, when you call the worksheet's `setCellValue()` method or the cell's `setValue()` method, PhpSpreadsheet will use the appropriate datatype for PHP nulls, booleans, floats or integers; or cast any string data value that you pass to the method into the most appropriate datatype, so numeric strings will be cast to numbers, while string values beginning with “=” will be converted to a formula. Strings that aren't numeric, or that don't begin with a leading "=" will be treated as genuine string values. +By default, when you call the worksheet's `setCellValue()` method or the +cell's `setValue()` method, PhpSpreadsheet will use the appropriate +datatype for PHP nulls, booleans, floats or integers; or cast any string +data value that you pass to the method into the most appropriate +datatype, so numeric strings will be cast to numbers, while string +values beginning with “=” will be converted to a formula. Strings that +aren't numeric, or that don't begin with a leading "=" will be treated +as genuine string values. -This "conversion" is handled by a cell "value binder", and you can write custom "value binders" to change the behaviour of these "conversions". The standard PhpSpreadsheet package also provides an "advanced value binder" that handles a number of more complex conversions, such as converting strings with a fractional format like "3/4" to a number value (0.75 in this case) and setting an appropriate "fraction" number format mask. Similarly, strings like "5%" will be converted to a value of 0.05, and a percentage number format mask applied, and strings containing values that look like dates will be converted to Excel serialized datetimestamp values, and a corresponding mask applied. This is particularly useful when loading data from csv files, or setting cell values from a database. +This "conversion" is handled by a cell "value binder", and you can write +custom "value binders" to change the behaviour of these "conversions". +The standard PhpSpreadsheet package also provides an "advanced value +binder" that handles a number of more complex conversions, such as +converting strings with a fractional format like "3/4" to a number value +(0.75 in this case) and setting an appropriate "fraction" number format +mask. Similarly, strings like "5%" will be converted to a value of 0.05, +and a percentage number format mask applied, and strings containing +values that look like dates will be converted to Excel serialized +datetimestamp values, and a corresponding mask applied. This is +particularly useful when loading data from csv files, or setting cell +values from a database. -Formats handled by the advanced value binder include - - TRUE or FALSE (dependent on locale settings) are converted to booleans. - - Numeric strings identified as scientific (exponential) format are converted to numbers. - - Fractions and vulgar fractions are converted to numbers, and an appropriate number format mask applied. - - Percentages are converted to numbers, divided by 100, and an appropriate number format mask applied. - - Dates and times are converted to Excel timestamp values (numbers), and an appropriate number format mask applied. - - When strings contain a newline character ("\n"), then the cell styling is set to wrap. +Formats handled by the advanced value binder include - TRUE or FALSE +(dependent on locale settings) are converted to booleans. - Numeric +strings identified as scientific (exponential) format are converted to +numbers. - Fractions and vulgar fractions are converted to numbers, and +an appropriate number format mask applied. - Percentages are converted +to numbers, divided by 100, and an appropriate number format mask +applied. - Dates and times are converted to Excel timestamp values +(numbers), and an appropriate number format mask applied. - When strings +contain a newline character ("\n"), then the cell styling is set to +wrap. -You can read more about value binders later in this section of the documentation. +You can read more about value binders later in this section of the +documentation. ### Setting a date and/or time value in a cell -Date or time values are held as timestamp in Excel (a simple floating point value), and a number format mask is used to show how that value should be formatted; so if we want to store a date in a cell, we need to calculate the correct Excel timestamp, and set a number format mask. +Date or time values are held as timestamp in Excel (a simple floating +point value), and a number format mask is used to show how that value +should be formatted; so if we want to store a date in a cell, we need to +calculate the correct Excel timestamp, and set a number format mask. -```php +``` php // Get the current date/time and convert to an Excel date/time $dateTimeNow = time(); $excelDateValue = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel( $dateTimeNow ); @@ -351,15 +467,23 @@ $spreadsheet->getActiveSheet()->getStyle('A6') ### Setting a number with leading zeroes -By default, PhpSpreadsheet will automatically detect the value type and set it to the appropriate Excel numeric datatype. This type conversion is handled by a value binder, as described in the section of this document entitled "Using value binders to facilitate data entry". +By default, PhpSpreadsheet will automatically detect the value type and +set it to the appropriate Excel numeric datatype. This type conversion +is handled by a value binder, as described in the section of this +document entitled "Using value binders to facilitate data entry". -Numbers don't have leading zeroes, so if you try to set a numeric value that does have leading zeroes (such as a telephone number) then these will be normally be lost as the value is cast to a number, so "01513789642" will be displayed as 1513789642. +Numbers don't have leading zeroes, so if you try to set a numeric value +that does have leading zeroes (such as a telephone number) then these +will be normally be lost as the value is cast to a number, so +"01513789642" will be displayed as 1513789642. -There are two ways you can force PhpSpreadsheet to override this behaviour. +There are two ways you can force PhpSpreadsheet to override this +behaviour. -Firstly, you can set the datatype explicitly as a string so that it is not converted to a number. +Firstly, you can set the datatype explicitly as a string so that it is +not converted to a number. -```php +``` php // Set cell A8 with a numeric value, but tell PhpSpreadsheet it should be treated as a string $spreadsheet->getActiveSheet()->setCellValueExplicit( 'A8', @@ -368,9 +492,10 @@ $spreadsheet->getActiveSheet()->setCellValueExplicit( ); ``` -Alternatively, you can use a number format mask to display the value with leading zeroes. +Alternatively, you can use a number format mask to display the value +with leading zeroes. -```php +``` php // Set cell A9 with a numeric value $spreadsheet->getActiveSheet()->setCellValue('A9', 1513789642); // Set a number format mask to display the value as 11 digits with leading zeroes @@ -381,9 +506,10 @@ $spreadsheet->getActiveSheet()->getStyle('A9') ); ``` -With number format masking, you can even break up the digits into groups to make the value more easily readable. +With number format masking, you can even break up the digits into groups +to make the value more easily readable. -```php +``` php // Set cell A10 with a numeric value $spreadsheet->getActiveSheet()->setCellValue('A10', 1513789642); // Set a number format mask to display the value as 11 digits with leading zeroes @@ -394,16 +520,19 @@ $spreadsheet->getActiveSheet()->getStyle('A10') ); ``` -![07-simple-example-1.png](./images/07-simple-example-1.png "") +![07-simple-example-1.png](./images/07-simple-example-1.png) - -**Note** that not all complex format masks such as this one will work when retrieving a formatted value to display "on screen", or for certain writers such as HTML or PDF, but it will work with the true spreadsheet writers (Xlsx and Xls). +**Note** that not all complex format masks such as this one will work +when retrieving a formatted value to display "on screen", or for certain +writers such as HTML or PDF, but it will work with the true spreadsheet +writers (Xlsx and Xls). ## Setting a range of cells from an array -It is also possible to set a range of cell values in a single call by passing an array of values to the `fromArray()` method. +It is also possible to set a range of cell values in a single call by +passing an array of values to the `fromArray()` method. -```php +``` php $arrayData = array( array(NULL, 2010, 2011, 2012), array('Q1', 12, 15, 21), @@ -420,11 +549,13 @@ $spreadsheet->getActiveSheet() ); ``` -![07-simple-example-2.png](./images/07-simple-example-2.png "") +![07-simple-example-2.png](./images/07-simple-example-2.png) -If you pass a 2-d array, then this will be treated as a series of rows and columns. A 1-d array will be treated as a single row, which is particularly useful if you're fetching an array of data from a database. +If you pass a 2-d array, then this will be treated as a series of rows +and columns. A 1-d array will be treated as a single row, which is +particularly useful if you're fetching an array of data from a database. -```php +``` php $rowArray = array('Value1', 'Value2', 'Value3', 'Value4'); $spreadsheet->getActiveSheet() ->fromArray( @@ -435,11 +566,13 @@ $spreadsheet->getActiveSheet() ); ``` -![07-simple-example-3.png](./images/07-simple-example-3.png "") +![07-simple-example-3.png](./images/07-simple-example-3.png) -If you have a simple 1-d array, and want to write it as a column, then the following will convert it into an appropriately structured 2-d array that can be fed to the `fromArray()` method: +If you have a simple 1-d array, and want to write it as a column, then +the following will convert it into an appropriately structured 2-d array +that can be fed to the `fromArray()` method: -```php +``` php $rowArray = array('Value1', 'Value2', 'Value3', 'Value4'); $columnArray = array_chunk($rowArray, 1); $spreadsheet->getActiveSheet() @@ -451,13 +584,15 @@ $spreadsheet->getActiveSheet() ); ``` -![07-simple-example-4.png](./images/07-simple-example-4.png "") +![07-simple-example-4.png](./images/07-simple-example-4.png) ## Retrieving a cell value by coordinate -To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the `getCell()` method. A cell's value can be read using the `getValue()` method. +To retrieve the value of a cell, the cell should first be retrieved from +the worksheet using the `getCell()` method. A cell's value can be read +using the `getValue()` method. -```php +``` php // Get the value fom cell A1 $cellValue = $spreadsheet->getActiveSheet()->getCell('A1') ->getValue(); @@ -465,46 +600,55 @@ $cellValue = $spreadsheet->getActiveSheet()->getCell('A1') This will retrieve the raw, unformatted value contained in the cell. -If a cell contains a formula, and you need to retrieve the calculated value rather than the formula itself, then use the cell's `getCalculatedValue()` method. This is further explained in . +If a cell contains a formula, and you need to retrieve the calculated +value rather than the formula itself, then use the cell's +`getCalculatedValue()` method. This is further explained in . -```php +``` php // Get the value fom cell A4 $cellValue = $spreadsheet->getActiveSheet()->getCell('A4') ->getCalculatedValue(); ``` -Alternatively, if you want to see the value with any cell formatting applied (e.g. for a human-readable date or time value), then you can use the cell's `getFormattedValue()` method. +Alternatively, if you want to see the value with any cell formatting +applied (e.g. for a human-readable date or time value), then you can use +the cell's `getFormattedValue()` method. -```php +``` php // Get the value fom cell A6 $cellValue = $spreadsheet->getActiveSheet()->getCell('A6') ->getFormattedValue(); ``` - ## Setting a cell value by column and row -Setting a cell value by coordinate can be done using the worksheet's `setCellValueByColumnAndRow()` method. +Setting a cell value by coordinate can be done using the worksheet's +`setCellValueByColumnAndRow()` method. -```php +``` php // Set cell B5 with a string value $spreadsheet->getActiveSheet()->setCellValueByColumnAndRow(1, 5, 'PhpSpreadsheet'); ``` -**Note** that column references start with '0' for column 'A', rather than from '1'. +**Note** that column references start with '0' for column 'A', rather +than from '1'. ## Retrieving a cell value by column and row -To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the getCellByColumnAndRow method. A cell’s value can be read again using the following line of code: +To retrieve the value of a cell, the cell should first be retrieved from +the worksheet using the getCellByColumnAndRow method. A cell’s value can +be read again using the following line of code: -```php +``` php // Get the value fom cell B5 $cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(1, 5) ->getValue(); ``` -If you need the calculated value of a cell, use the following code. This is further explained in . -```php +If you need the calculated value of a cell, use the following code. This +is further explained in . + +``` php // Get the value fom cell A4 $cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(0, 4) ->getCalculatedValue(); @@ -512,9 +656,11 @@ $cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(0, 4) ## Retrieving a range of cell values to an array -It is also possible to retrieve a range of cell values to an array in a single call using the `toArray()`, `rangeToArray()` or `namedRangeToArray()` methods. +It is also possible to retrieve a range of cell values to an array in a +single call using the `toArray()`, `rangeToArray()` or +`namedRangeToArray()` methods. -```php +``` php $dataArray = $spreadsheet->getActiveSheet() ->rangeToArray( 'C3:E5', // The worksheet range that we want to retrieve @@ -525,17 +671,23 @@ $dataArray = $spreadsheet->getActiveSheet() ); ``` -These methods will all return a 2-d array of rows and columns. The `toArray()` method will return the whole worksheet; `rangeToArray()` will return a specified range or cells; while `namedRangeToArray()` will return the cells within a defined `named range`. +These methods will all return a 2-d array of rows and columns. The +`toArray()` method will return the whole worksheet; `rangeToArray()` +will return a specified range or cells; while `namedRangeToArray()` will +return the cells within a defined `named range`. ## Looping through cells ### Looping through cells using iterators -The easiest way to loop cells is by using iterators. Using iterators, one can use foreach to loop worksheets, rows within a worksheet, and cells within a row. +The easiest way to loop cells is by using iterators. Using iterators, +one can use foreach to loop worksheets, rows within a worksheet, and +cells within a row. -Below is an example where we read all the values in a worksheet and display them in a table. +Below is an example where we read all the values in a worksheet and +display them in a table. -```php +``` php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->load("test.xlsx"); @@ -560,20 +712,30 @@ foreach ($worksheet->getRowIterator() as $row) { echo '' . PHP_EOL; ``` -Note that we have set the cell iterator's `setIterateOnlyExistingCells()` to FALSE. This makes the iterator loop all cells within the worksheet range, even if they have not been set. +Note that we have set the cell iterator's +`setIterateOnlyExistingCells()` to FALSE. This makes the iterator loop +all cells within the worksheet range, even if they have not been set. -The cell iterator will return a __NULL__ as the cell value if it is not set in the worksheet. -Setting the cell iterator's setIterateOnlyExistingCells() to FALSE will loop all cells in the worksheet that can be available at that moment. This will create new cells if required and increase memory usage! Only use it if it is intended to loop all cells that are possibly available. +The cell iterator will return a **NULL** as the cell value if it is not +set in the worksheet. Setting the cell iterator's +setIterateOnlyExistingCells() to FALSE will loop all cells in the +worksheet that can be available at that moment. This will create new +cells if required and increase memory usage! Only use it if it is +intended to loop all cells that are possibly available. ### Looping through cells using indexes -One can use the possibility to access cell values by column and row index like (0,1) instead of 'A1' for reading and writing cell values in loops. +One can use the possibility to access cell values by column and row +index like (0,1) instead of 'A1' for reading and writing cell values in +loops. -Note: In PhpSpreadsheet column index is 0-based while row index is 1-based. That means 'A1' ~ (0,1) +Note: In PhpSpreadsheet column index is 0-based while row index is +1-based. That means 'A1' \~ (0,1) -Below is an example where we read all the values in a worksheet and display them in a table. +Below is an example where we read all the values in a worksheet and +display them in a table. -```php +``` php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->load("test.xlsx"); @@ -598,9 +760,10 @@ for ($row = 1; $row <= $highestRow; ++$row) { echo '' . PHP_EOL; ``` -Alternatively, you can take advantage of PHP's "Perl-style" character incrementors to loop through the cells by coordinate: +Alternatively, you can take advantage of PHP's "Perl-style" character +incrementors to loop through the cells by coordinate: -```php +``` php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->load("test.xlsx"); @@ -626,15 +789,27 @@ for ($row = 1; $row <= $highestRow; ++$row) { echo '' . PHP_EOL; ``` -Note that we can't use a <= comparison here, because 'AA' would match as <= 'B', so we increment the highest column letter and then loop while $col != the incremented highest column. +Note that we can't use a <= comparison here, because 'AA' would match +as <= 'B', so we increment the highest column letter and then loop +while \$col != the incremented highest column. ## Using value binders to facilitate data entry -Internally, PhpSpreadsheet uses a default \PhpOffice\PhpSpreadsheet\Cell\IValueBinder implementation (\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder) to determine data types of entered data using a cell's `setValue()` method (the `setValueExplicit()` method bypasses this check). +Internally, PhpSpreadsheet uses a default +\PhpOffice\PhpSpreadsheet\Cell\IValueBinder implementation +(\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder) to determine data +types of entered data using a cell's `setValue()` method (the +`setValueExplicit()` method bypasses this check). -Optionally, the default behaviour of PhpSpreadsheet can be modified, allowing easier data entry. For example, a \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder class is available. It automatically converts percentages, number in scientific format, and dates entered as strings to the correct format, also setting the cell's style information. The following example demonstrates how to set the value binder in PhpSpreadsheet: +Optionally, the default behaviour of PhpSpreadsheet can be modified, +allowing easier data entry. For example, a +\PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder class is available. +It automatically converts percentages, number in scientific format, and +dates entered as strings to the correct format, also setting the cell's +style information. The following example demonstrates how to set the +value binder in PhpSpreadsheet: -```php +``` php /** PhpSpreadsheet */ require_once 'src/Boostrap.php'; @@ -655,62 +830,91 @@ $spreadsheet->getActiveSheet()->setCellValue('A5', 'Date/time value:'); $spreadsheet->getActiveSheet()->setCellValue('B5', '21 December 1983'); ``` -__Creating your own value binder is easy.__ -When advanced value binding is required, you can implement the \PhpOffice\PhpSpreadsheet\Cell\IValueBinder interface or extend the \PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder or \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder classes. +**Creating your own value binder is easy.** When advanced value binding +is required, you can implement the +\PhpOffice\PhpSpreadsheet\Cell\IValueBinder interface or extend the +\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder or +\PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder classes. # Reading and writing to file -As you already know from part REF _Ref191885438 \w \h 3.3 REF _Ref191885438 \h Readers and writers, reading and writing to a persisted storage is not possible using the base PhpSpreadsheet classes. For this purpose, PhpSpreadsheet provides readers and writers, which are implementations of \PhpOffice\PhpSpreadsheet\Reader\IReader and \PhpOffice\PhpSpreadsheet\Writer\IWriter. +As you already know from part REF \_Ref191885438 \w \h 3.3 REF +\_Ref191885438 \h Readers and writers, reading and writing to a +persisted storage is not possible using the base PhpSpreadsheet classes. +For this purpose, PhpSpreadsheet provides readers and writers, which are +implementations of \PhpOffice\PhpSpreadsheet\Reader\IReader and +\PhpOffice\PhpSpreadsheet\Writer\IWriter. ## \PhpOffice\PhpSpreadsheet\IOFactory -The PhpSpreadsheet API offers multiple methods to create a \PhpOffice\PhpSpreadsheet\Reader\IReader or \PhpOffice\PhpSpreadsheet\Writer\IWriter instance: +The PhpSpreadsheet API offers multiple methods to create a +\PhpOffice\PhpSpreadsheet\Reader\IReader or +\PhpOffice\PhpSpreadsheet\Writer\IWriter instance: -Direct creation via \PhpOffice\PhpSpreadsheet\IOFactory. All examples underneath demonstrate the direct creation method. Note that you can also use the \PhpOffice\PhpSpreadsheet\IOFactory class to do this. +Direct creation via \PhpOffice\PhpSpreadsheet\IOFactory. All examples +underneath demonstrate the direct creation method. Note that you can +also use the \PhpOffice\PhpSpreadsheet\IOFactory class to do this. ### Creating \PhpOffice\PhpSpreadsheet\Reader\IReader using \PhpOffice\PhpSpreadsheet\IOFactory -There are 2 methods for reading in a file into PhpSpreadsheet: using automatic file type resolving or explicitly. +There are 2 methods for reading in a file into PhpSpreadsheet: using +automatic file type resolving or explicitly. -Automatic file type resolving checks the different \PhpOffice\PhpSpreadsheet\Reader\IReader distributed with PhpSpreadsheet. If one of them can load the specified file name, the file is loaded using that \PhpOffice\PhpSpreadsheet\Reader\IReader. Explicit mode requires you to specify which \PhpOffice\PhpSpreadsheet\Reader\IReader should be used. +Automatic file type resolving checks the different +\PhpOffice\PhpSpreadsheet\Reader\IReader distributed with +PhpSpreadsheet. If one of them can load the specified file name, the +file is loaded using that \PhpOffice\PhpSpreadsheet\Reader\IReader. +Explicit mode requires you to specify which +\PhpOffice\PhpSpreadsheet\Reader\IReader should be used. -You can create a \PhpOffice\PhpSpreadsheet\Reader\IReader instance using \PhpOffice\PhpSpreadsheet\IOFactory in automatic file type resolving mode using the following code sample: +You can create a \PhpOffice\PhpSpreadsheet\Reader\IReader instance using +\PhpOffice\PhpSpreadsheet\IOFactory in automatic file type resolving +mode using the following code sample: -```php +``` php $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("05featuredemo.xlsx"); ``` -A typical use of this feature is when you need to read files uploaded by your users, and you don’t know whether they are uploading xls or xlsx files. +A typical use of this feature is when you need to read files uploaded by +your users, and you don’t know whether they are uploading xls or xlsx +files. -If you need to set some properties on the reader, (e.g. to only read data, see more about this later), then you may instead want to use this variant: +If you need to set some properties on the reader, (e.g. to only read +data, see more about this later), then you may instead want to use this +variant: -```php +``` php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx"); $reader->setReadDataOnly(true); $reader->load("05featuredemo.xlsx"); ``` -You can create a \PhpOffice\PhpSpreadsheet\Reader\IReader instance using \PhpOffice\PhpSpreadsheet\IOFactory in explicit mode using the following code sample: +You can create a \PhpOffice\PhpSpreadsheet\Reader\IReader instance using +\PhpOffice\PhpSpreadsheet\IOFactory in explicit mode using the following +code sample: -```php +``` php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx"); $spreadsheet = $reader->load("05featuredemo.xlsx"); ``` -Note that automatic type resolving mode is slightly slower than explicit mode. +Note that automatic type resolving mode is slightly slower than explicit +mode. ### Creating \PhpOffice\PhpSpreadsheet\Writer\IWriter using \PhpOffice\PhpSpreadsheet\IOFactory -You can create a PhpOffice\PhpSpreadsheet\Writer\IWriter instance using \PhpOffice\PhpSpreadsheet\IOFactory: +You can create a PhpOffice\PhpSpreadsheet\Writer\IWriter instance using +\PhpOffice\PhpSpreadsheet\IOFactory: -```php +``` php $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx"); $writer->save("05featuredemo.xlsx"); ``` ## Excel 2007 (SpreadsheetML) file format -Xlsx file format is the main file format of PhpSpreadsheet. It allows outputting the in-memory spreadsheet to a .xlsx file. +Xlsx file format is the main file format of PhpSpreadsheet. It allows +outputting the in-memory spreadsheet to a .xlsx file. ### \PhpOffice\PhpSpreadsheet\Reader\Xlsx @@ -718,16 +922,17 @@ Xlsx file format is the main file format of PhpSpreadsheet. It allows outputting You can read an .xlsx file using the following code: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $spreadsheet = $reader->load("05featuredemo.xlsx"); ``` #### Read data only -You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data: +You can set the option setReadDataOnly on the reader, to instruct the +reader to ignore styling, data validation, … and just read cell data: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $reader->setReadDataOnly(true); $spreadsheet = $reader->load("05featuredemo.xlsx"); @@ -735,9 +940,10 @@ $spreadsheet = $reader->load("05featuredemo.xlsx"); #### Read specific sheets only -You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name: +You can set the option setLoadSheetsOnly on the reader, to instruct the +reader to only load the sheets with a given name: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); $reader->setLoadSheetsOnly( array("Sheet 1", "My special sheet") ); $spreadsheet = $reader->load("05featuredemo.xlsx"); @@ -745,11 +951,16 @@ $spreadsheet = $reader->load("05featuredemo.xlsx"); #### Read specific cells only -You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. +You can set the option setReadFilter on the reader, to instruct the +reader to only load the cells which match a given rule. A read filter +can be any class which implements +\PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are +read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. -The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file: +The following code will only read row 1 and rows 20 – 30 of any sheet in +the Excel file: -```php +``` php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($column, $row, $worksheetName = '') { @@ -772,16 +983,18 @@ $spreadsheet = $reader->load("06largescale.xlsx"); You can write an .xlsx file using the following code: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); $writer->save("05featuredemo.xlsx"); ``` #### Formula pre-calculation -By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation: +By default, this writer pre-calculates all formulas in the spreadsheet. +This can be slow on large spreadsheets, and maybe even unwanted. You can +however disable formula pre-calculation: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); $writer->setPreCalculateFormulas(false); $writer->save("05featuredemo.xlsx"); @@ -789,25 +1002,37 @@ $writer->save("05featuredemo.xlsx"); #### Office 2003 compatibility pack -Because of a bug in the Office2003 compatibility pack, there can be some small issues when opening Xlsx spreadsheets (mostly related to formula calculation). You can enable Office2003 compatibility with the following code: +Because of a bug in the Office2003 compatibility pack, there can be some +small issues when opening Xlsx spreadsheets (mostly related to formula +calculation). You can enable Office2003 compatibility with the following +code: -``` -$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); -$writer->setOffice2003Compatibility(true); -$writer->save("05featuredemo.xlsx"); -``` + $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); + $writer->setOffice2003Compatibility(true); + $writer->save("05featuredemo.xlsx"); -__Office2003 compatibility should only be used when needed__ -Office2003 compatibility option should only be used when needed. This option disables several Office2007 file format options, resulting in a lower-featured Office2007 spreadsheet when this option is used. +**Office2003 compatibility should only be used when needed** Office2003 +compatibility option should only be used when needed. This option +disables several Office2007 file format options, resulting in a +lower-featured Office2007 spreadsheet when this option is used. ## Excel 5 (BIFF) file format -Xls file format is the old Excel file format, implemented in PhpSpreadsheet to provide a uniform manner to create both .xlsx and .xls files. It is basically a modified version of [PEAR Spreadsheet_Excel_Writer](http://pear.php.net/package/Spreadsheet_Excel_Writer), although it has been extended and has fewer limitations and more features than the old PEAR library. This can read all BIFF versions that use OLE2: BIFF5 (introduced with office 95) through BIFF8, but cannot read earlier versions. +Xls file format is the old Excel file format, implemented in +PhpSpreadsheet to provide a uniform manner to create both .xlsx and .xls +files. It is basically a modified version of [PEAR +Spreadsheet\_Excel\_Writer](http://pear.php.net/package/Spreadsheet_Excel_Writer), +although it has been extended and has fewer limitations and more +features than the old PEAR library. This can read all BIFF versions that +use OLE2: BIFF5 (introduced with office 95) through BIFF8, but cannot +read earlier versions. -Xls file format will not be developed any further, it just provides an additional file format for PhpSpreadsheet. +Xls file format will not be developed any further, it just provides an +additional file format for PhpSpreadsheet. -__Excel5 (BIFF) limitations__ -Please note that BIFF file format has some limits regarding to styling cells and handling large spreadsheets via PHP. +**Excel5 (BIFF) limitations** Please note that BIFF file format has some +limits regarding to styling cells and handling large spreadsheets via +PHP. ### \PhpOffice\PhpSpreadsheet\Reader\Xls @@ -815,16 +1040,17 @@ Please note that BIFF file format has some limits regarding to styling cells and You can read an .xls file using the following code: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); $spreadsheet = $reader->load("05featuredemo.xls"); ``` #### Read data only -You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data: +You can set the option setReadDataOnly on the reader, to instruct the +reader to ignore styling, data validation, … and just read cell data: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); $reader->setReadDataOnly(true); $spreadsheet = $reader->load("05featuredemo.xls"); @@ -832,9 +1058,10 @@ $spreadsheet = $reader->load("05featuredemo.xls"); #### Read specific sheets only -You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name: +You can set the option setLoadSheetsOnly on the reader, to instruct the +reader to only load the sheets with a given name: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); $reader->setLoadSheetsOnly( array("Sheet 1", "My special sheet") ); $spreadsheet = $reader->load("05featuredemo.xls"); @@ -842,11 +1069,16 @@ $spreadsheet = $reader->load("05featuredemo.xls"); #### Read specific cells only -You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. +You can set the option setReadFilter on the reader, to instruct the +reader to only load the cells which match a given rule. A read filter +can be any class which implements +\PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are +read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. -The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file: +The following code will only read row 1 and rows 20 to 30 of any sheet +in the Excel file: -```php +``` php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($column, $row, $worksheetName = '') { @@ -869,17 +1101,19 @@ $spreadsheet = $reader->load("06largescale.xls"); You can write an .xls file using the following code: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xls($spreadsheet); $writer->save("05featuredemo.xls"); ``` ## Excel 2003 XML file format -Excel 2003 XML file format is a file format which can be used in older versions of Microsoft Excel. +Excel 2003 XML file format is a file format which can be used in older +versions of Microsoft Excel. -__Excel 2003 XML limitations__ -Please note that Excel 2003 XML format has some limits regarding to styling cells and handling large spreadsheets via PHP. +**Excel 2003 XML limitations** Please note that Excel 2003 XML format +has some limits regarding to styling cells and handling large +spreadsheets via PHP. ### \PhpOffice\PhpSpreadsheet\Reader\Excel2003XML @@ -887,18 +1121,23 @@ Please note that Excel 2003 XML format has some limits regarding to styling cell You can read an Excel 2003 .xml file using the following code: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Excel2003XML(); $spreadsheet = $reader->load("05featuredemo.xml"); ``` #### Read specific cells only -You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. +You can set the option setReadFilter on the reader, to instruct the +reader to only load the cells which match a given rule. A read filter +can be any class which implements +\PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are +read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. -The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file: +The following code will only read row 1 and rows 20 to 30 of any sheet +in the Excel file: -```php +``` php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($column, $row, $worksheetName = '') { @@ -918,10 +1157,14 @@ $spreadsheet = $reader->load("06largescale.xml"); ## Symbolic LinK (SYLK) -Symbolic Link (SYLK) is a Microsoft file format typically used to exchange data between applications, specifically spreadsheets. SYLK files conventionally have a .slk suffix. Composed of only displayable ANSI characters, it can be easily created and processed by other applications, such as databases. +Symbolic Link (SYLK) is a Microsoft file format typically used to +exchange data between applications, specifically spreadsheets. SYLK +files conventionally have a .slk suffix. Composed of only displayable +ANSI characters, it can be easily created and processed by other +applications, such as databases. -__SYLK limitations__ -Please note that SYLK file format has some limits regarding to styling cells and handling large spreadsheets via PHP. +**SYLK limitations** Please note that SYLK file format has some limits +regarding to styling cells and handling large spreadsheets via PHP. ### \PhpOffice\PhpSpreadsheet\Reader\SYLK @@ -929,18 +1172,23 @@ Please note that SYLK file format has some limits regarding to styling cells and You can read an .slk file using the following code: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\SYLK(); $spreadsheet = $reader->load("05featuredemo.slk"); ``` #### Read specific cells only -You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. +You can set the option setReadFilter on the reader, to instruct the +reader to only load the cells which match a given rule. A read filter +can be any class which implements +\PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are +read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. -The following code will only read row 1 and rows 20 to 30 of any sheet in the SYLK file: +The following code will only read row 1 and rows 20 to 30 of any sheet +in the SYLK file: -```php +``` php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($column, $row, $worksheetName = '') { @@ -960,7 +1208,8 @@ $spreadsheet = $reader->load("06largescale.slk"); ## Open/Libre Office (.ods) -Open Office or Libre Office .ods files are the standard file format for Open Office or Libre Office Calc files. +Open Office or Libre Office .ods files are the standard file format for +Open Office or Libre Office Calc files. ### \PhpOffice\PhpSpreadsheet\Reader\Ods @@ -968,18 +1217,23 @@ Open Office or Libre Office .ods files are the standard file format for Open Off You can read an .ods file using the following code: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\Ods(); $spreadsheet = $reader->load("05featuredemo.ods"); ``` #### Read specific cells only -You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. +You can set the option setReadFilter on the reader, to instruct the +reader to only load the cells which match a given rule. A read filter +can be any class which implements +\PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are +read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter. -The following code will only read row 1 and rows 20 to 30 of any sheet in the Calc file: +The following code will only read row 1 and rows 20 to 30 of any sheet +in the Calc file: -```php +``` php class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { public function readCell($column, $row, $worksheetName = '') { @@ -999,10 +1253,12 @@ $spreadsheet = $reader->load("06largescale.ods"); ## CSV (Comma Separated Values) -CSV (Comma Separated Values) are often used as an import/export file format with other systems. PhpSpreadsheet allows reading and writing to CSV files. +CSV (Comma Separated Values) are often used as an import/export file +format with other systems. PhpSpreadsheet allows reading and writing to +CSV files. -__CSV limitations__ -Please note that CSV file format has some limits regarding to styling cells, number formatting, ... +**CSV limitations** Please note that CSV file format has some limits +regarding to styling cells, number formatting, ... ### \PhpOffice\PhpSpreadsheet\Reader\CSV @@ -1010,18 +1266,25 @@ Please note that CSV file format has some limits regarding to styling cells, num You can read a .csv file using the following code: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\CSV(); $spreadsheet = $reader->load("sample.csv"); ``` #### Setting CSV options -Often, CSV files are not really “comma separated”, or use semicolon (;) as a separator. You can instruct \PhpOffice\PhpSpreadsheet\Reader\CSV some options before reading a CSV file. +Often, CSV files are not really “comma separated”, or use semicolon (;) +as a separator. You can instruct +\PhpOffice\PhpSpreadsheet\Reader\CSV some options before reading a CSV +file. -Note that \PhpOffice\PhpSpreadsheet\Reader\CSV by default assumes that the loaded CSV file is UTF-8 encoded. If you are reading CSV files that were created in Microsoft Office Excel the correct input encoding may rather be Windows-1252 (CP1252). Always make sure that the input encoding is set appropriately. +Note that \PhpOffice\PhpSpreadsheet\Reader\CSV by default assumes that +the loaded CSV file is UTF-8 encoded. If you are reading CSV files that +were created in Microsoft Office Excel the correct input encoding may +rather be Windows-1252 (CP1252). Always make sure that the input +encoding is set appropriately. -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\CSV(); $reader->setInputEncoding('CP1252'); $reader->setDelimiter(';'); @@ -1034,17 +1297,21 @@ $spreadsheet = $reader->load("sample.csv"); #### Read a specific worksheet -CSV files can only contain one worksheet. Therefore, you can specify which sheet to read from CSV: +CSV files can only contain one worksheet. Therefore, you can specify +which sheet to read from CSV: -```php +``` php $reader->setSheetIndex(0); ``` #### Read into existing spreadsheet -When working with CSV files, it might occur that you want to import CSV data into an existing `Spreadsheet` object. The following code loads a CSV file into an existing $spreadsheet containing some sheets, and imports onto the 6th sheet: +When working with CSV files, it might occur that you want to import CSV +data into an existing `Spreadsheet` object. The following code loads a +CSV file into an existing \$spreadsheet containing some sheets, and +imports onto the 6th sheet: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\CSV(); $reader->setDelimiter(';'); $reader->setEnclosure(''); @@ -1060,16 +1327,19 @@ $reader->loadIntoExisting("05featuredemo.csv", $spreadsheet); You can write a .csv file using the following code: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\CSV($spreadsheet); $writer->save("05featuredemo.csv"); ``` #### Setting CSV options -Often, CSV files are not really “comma separated”, or use semicolon (;) as a separator. You can instruct \PhpOffice\PhpSpreadsheet\Writer\CSV some options before writing a CSV file: +Often, CSV files are not really “comma separated”, or use semicolon (;) +as a separator. You can instruct +\PhpOffice\PhpSpreadsheet\Writer\CSV some options before writing a CSV +file: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\CSV($spreadsheet); $writer->setDelimiter(';'); $writer->setEnclosure(''); @@ -1081,17 +1351,20 @@ $writer->save("05featuredemo.csv"); #### Write a specific worksheet -CSV files can only contain one worksheet. Therefore, you can specify which sheet to write to CSV: +CSV files can only contain one worksheet. Therefore, you can specify +which sheet to write to CSV: -```php +``` php $writer->setSheetIndex(0); ``` #### Formula pre-calculation -By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation: +By default, this writer pre-calculates all formulas in the spreadsheet. +This can be slow on large spreadsheets, and maybe even unwanted. You can +however disable formula pre-calculation: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\CSV($spreadsheet); $writer->setPreCalculateFormulas(false); $writer->save("05featuredemo.csv"); @@ -1099,9 +1372,10 @@ $writer->save("05featuredemo.csv"); #### Writing UTF-8 CSV files -A CSV file can be marked as UTF-8 by writing a BOM file header. This can be enabled by using the following code: +A CSV file can be marked as UTF-8 by writing a BOM file header. This can +be enabled by using the following code: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\CSV($spreadsheet); $writer->setUseBOM(true); $writer->save("05featuredemo.csv"); @@ -1109,32 +1383,41 @@ $writer->save("05featuredemo.csv"); #### Decimal and thousands separators -If the worksheet you are exporting contains numbers with decimal or thousands separators then you should think about what characters you want to use for those before doing the export. +If the worksheet you are exporting contains numbers with decimal or +thousands separators then you should think about what characters you +want to use for those before doing the export. -By default PhpSpreadsheet looks up in the server's locale settings to decide what characters to use. But to avoid problems it is recommended to set the characters explicitly as shown below. +By default PhpSpreadsheet looks up in the server's locale settings to +decide what characters to use. But to avoid problems it is recommended +to set the characters explicitly as shown below. English users will want to use this before doing the export: -```php +``` php \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator('.'); \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator(','); ``` German users will want to use the opposite values. -```php +``` php \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator(','); \PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator('.'); ``` -Note that the above code sets decimal and thousand separators as global options. This also affects how HTML and PDF is exported. +Note that the above code sets decimal and thousand separators as global +options. This also affects how HTML and PDF is exported. ## HTML -PhpSpreadsheet allows you to read or write a spreadsheet as HTML format, for quick representation of the data in it to anyone who does not have a spreadsheet application on their PC, or loading files saved by other scripts that simply create HTML markup and give it a .xls file extension. +PhpSpreadsheet allows you to read or write a spreadsheet as HTML format, +for quick representation of the data in it to anyone who does not have a +spreadsheet application on their PC, or loading files saved by other +scripts that simply create HTML markup and give it a .xls file +extension. -__HTML limitations__ -Please note that HTML file format has some limits regarding to styling cells, number formatting, ... +**HTML limitations** Please note that HTML file format has some limits +regarding to styling cells, number formatting, ... ### \PhpOffice\PhpSpreadsheet\Reader\HTML @@ -1142,24 +1425,25 @@ Please note that HTML file format has some limits regarding to styling cells, nu You can read an .html or .htm file using the following code: -```php +``` php $reader = new \PhpOffice\PhpSpreadsheet\Reader\HTML(); $spreadsheet = $reader->load("05featuredemo.html"); ``` -__HTML limitations__ -Please note that HTML reader is still experimental and does not yet support merged cells or nested tables cleanly +**HTML limitations** Please note that HTML reader is still experimental +and does not yet support merged cells or nested tables cleanly ### \PhpOffice\PhpSpreadsheet\Writer\HTML -Please note that \PhpOffice\PhpSpreadsheet\Writer\HTML only outputs the first worksheet by default. +Please note that \PhpOffice\PhpSpreadsheet\Writer\HTML only outputs the +first worksheet by default. #### Writing a spreadsheet You can write a .htm file using the following code: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\HTML($spreadsheet); $writer->save("05featuredemo.htm"); @@ -1167,44 +1451,50 @@ $writer->save("05featuredemo.htm"); #### Write all worksheets -HTML files can contain one or more worksheets. If you want to write all sheets into a single HTML file, use the following code: +HTML files can contain one or more worksheets. If you want to write all +sheets into a single HTML file, use the following code: -```php +``` php $writer->writeAllSheets(); ``` #### Write a specific worksheet -HTML files can contain one or more worksheets. Therefore, you can specify which sheet to write to HTML: +HTML files can contain one or more worksheets. Therefore, you can +specify which sheet to write to HTML: -```php +``` php $writer->setSheetIndex(0); ``` #### Setting the images root of the HTML file -There might be situations where you want to explicitly set the included images root. For example, one might want to see -```html +There might be situations where you want to explicitly set the included +images root. For example, one might want to see + +``` html ``` instead of -```html +``` html . ``` You can use the following code to achieve this result: -```php +``` php $writer->setImagesRoot('http://www.example.com'); ``` #### Formula pre-calculation -By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation: +By default, this writer pre-calculates all formulas in the spreadsheet. +This can be slow on large spreadsheets, and maybe even unwanted. You can +however disable formula pre-calculation: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\HTML($spreadsheet); $writer->setPreCalculateFormulas(false); @@ -1213,18 +1503,22 @@ $writer->save("05featuredemo.htm"); #### Embedding generated HTML in a web page -There might be a situation where you want to embed the generated HTML in an existing website. \PhpOffice\PhpSpreadsheet\Writer\HTML provides support to generate only specific parts of the HTML code, which allows you to use these parts in your website. +There might be a situation where you want to embed the generated HTML in +an existing website. \PhpOffice\PhpSpreadsheet\Writer\HTML provides +support to generate only specific parts of the HTML code, which allows +you to use these parts in your website. Supported methods: - - generateHTMLHeader() - - generateStyles() - - generateSheetData() - - generateHTMLFooter() +- generateHTMLHeader() +- generateStyles() +- generateSheetData() +- generateHTMLFooter() -Here's an example which retrieves all parts independently and merges them into a resulting HTML page: +Here's an example which retrieves all parts independently and merges +them into a resulting HTML page: -```php +``` php generateHTMLHeader(); @@ -1253,9 +1547,10 @@ echo $writer->generateHTMLFooter(); #### Writing UTF-8 HTML files -A HTML file can be marked as UTF-8 by writing a BOM file header. This can be enabled by using the following code: +A HTML file can be marked as UTF-8 by writing a BOM file header. This +can be enabled by using the following code: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\HTML($spreadsheet); $writer->setUseBOM(true); @@ -1264,18 +1559,23 @@ $writer->save("05featuredemo.htm"); #### Decimal and thousands separators -See section \PhpOffice\PhpSpreadsheet\Writer\CSV how to control the appearance of these. +See section \PhpOffice\PhpSpreadsheet\Writer\CSV how to control the +appearance of these. ## PDF -PhpSpreadsheet allows you to write a spreadsheet into PDF format, for fast distribution of represented data. +PhpSpreadsheet allows you to write a spreadsheet into PDF format, for +fast distribution of represented data. -__PDF limitations__ -Please note that PDF file format has some limits regarding to styling cells, number formatting, ... +**PDF limitations** Please note that PDF file format has some limits +regarding to styling cells, number formatting, ... ### \PhpOffice\PhpSpreadsheet\Writer\PDF -PhpSpreadsheet’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering library such as tcPDF, mPDF or DomPDF. You must now install a PDF Rendering library yourself; but PhpSpreadsheet will work with a number of different libraries. +PhpSpreadsheet’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering +library such as tcPDF, mPDF or DomPDF. You must now install a PDF +Rendering library yourself; but PhpSpreadsheet will work with a number +of different libraries. Currently, the following libraries are supported: @@ -1285,11 +1585,16 @@ tcPDF | 5.9 | http://www.tcpdf.org/ | PDF_REND mPDF | 5.4 | http://www.mpdf1.com/mpdf/ | PDF_RENDERER_MPDF domPDF | 0.6.0 beta 3 | http://code.google.com/p/dompdf/ | PDF_RENDERER_DOMPDF -The different libraries have different strengths and weaknesses. Some generate better formatted output than others, some are faster or use less memory than others, while some generate smaller .pdf files. It is the developers choice which one they wish to use, appropriate to their own circumstances. +The different libraries have different strengths and weaknesses. Some +generate better formatted output than others, some are faster or use +less memory than others, while some generate smaller .pdf files. It is +the developers choice which one they wish to use, appropriate to their +own circumstances. -Before instantiating a Writer to generate PDF output, you will need to indicate which Rendering library you are using, and where it is located. +Before instantiating a Writer to generate PDF output, you will need to +indicate which Rendering library you are using, and where it is located. -```php +``` php $rendererName = \PhpOffice\PhpSpreadsheet\Settings::PDF_RENDERER_MPDF; $rendererLibrary = 'mPDF5.4'; $rendererLibraryPath = dirname(__FILE__).'/../../../libraries/PDF/' . $rendererLibrary; @@ -1308,36 +1613,42 @@ if (!\PhpOffice\PhpSpreadsheet\Settings::setPdfRenderer( #### Writing a spreadsheet -Once you have identified the Renderer that you wish to use for PDF generation, you can write a .pdf file using the following code: +Once you have identified the Renderer that you wish to use for PDF +generation, you can write a .pdf file using the following code: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\PDF($spreadsheet); $writer->save("05featuredemo.pdf"); ``` -Please note that \PhpOffice\PhpSpreadsheet\Writer\PDF only outputs the first worksheet by default. +Please note that \PhpOffice\PhpSpreadsheet\Writer\PDF only outputs the +first worksheet by default. #### Write all worksheets -PDF files can contain one or more worksheets. If you want to write all sheets into a single PDF file, use the following code: +PDF files can contain one or more worksheets. If you want to write all +sheets into a single PDF file, use the following code: -```php +``` php $writer->writeAllSheets(); ``` #### Write a specific worksheet -PDF files can contain one or more worksheets. Therefore, you can specify which sheet to write to PDF: +PDF files can contain one or more worksheets. Therefore, you can specify +which sheet to write to PDF: -```php +``` php $writer->setSheetIndex(0); ``` #### Formula pre-calculation -By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation: +By default, this writer pre-calculates all formulas in the spreadsheet. +This can be slow on large spreadsheets, and maybe even unwanted. You can +however disable formula pre-calculation: -```php +``` php $writer = new \PhpOffice\PhpSpreadsheet\Writer\PDF($spreadsheet); $writer->setPreCalculateFormulas(false); @@ -1346,15 +1657,20 @@ $writer->save("05featuredemo.pdf"); #### Decimal and thousands separators -See section \PhpOffice\PhpSpreadsheet\Writer\CSV how to control the appearance of these. +See section \PhpOffice\PhpSpreadsheet\Writer\CSV how to control the +appearance of these. ## Generating Excel files from templates (read, modify, write) -Readers and writers are the tools that allow you to generate Excel files from templates. This requires less coding effort than generating the Excel file from scratch, especially if your template has many styles, page setup properties, headers etc. +Readers and writers are the tools that allow you to generate Excel files +from templates. This requires less coding effort than generating the +Excel file from scratch, especially if your template has many styles, +page setup properties, headers etc. -Here is an example how to open a template file, fill in a couple of fields and save it again: +Here is an example how to open a template file, fill in a couple of +fields and save it again: -```php +``` php $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx'); $worksheet = $spreadsheet->getActiveSheet(); @@ -1368,7 +1684,8 @@ $writer->save('write.xls'); Notice that it is ok to load an xlsx file and generate an xls file. - # Credits -Please refer to the internet page [contributor list](https://github.com/PHPOffice/PhpSpreadsheet/graphs/contributors) for up-to-date credits. +Please refer to the internet page [contributor +list](https://github.com/PHPOffice/PhpSpreadsheet/graphs/contributors) +for up-to-date credits. diff --git a/docs/topics/autofilters.md b/docs/topics/autofilters.md index 1fc0495e..679dd87a 100644 --- a/docs/topics/autofilters.md +++ b/docs/topics/autofilters.md @@ -1,37 +1,62 @@ # AutoFilter Reference - ## Introduction -Each worksheet in an Excel Workbook can contain a single autoFilter range. Filtered data displays only the rows that meet criteria that you specify and hides rows that you do not want displayed. You can filter by more than one column: filters are additive, which means that each additional filter is based on the current filter and further reduces the subset of data. +Each worksheet in an Excel Workbook can contain a single autoFilter +range. Filtered data displays only the rows that meet criteria that you +specify and hides rows that you do not want displayed. You can filter by +more than one column: filters are additive, which means that each +additional filter is based on the current filter and further reduces the +subset of data. -![01-01-autofilter.png](./images/01-01-autofilter.png "") +![01-01-autofilter.png](./images/01-01-autofilter.png) -When an AutoFilter is applied to a range of cells, the first row in an autofilter range will be the heading row, which displays the autoFilter dropdown icons. It is not part of the actual autoFiltered data. All subsequent rows are the autoFiltered data. So an AutoFilter range should always contain the heading row and one or more data rows (one data row is pretty meaningless), but PhpSpreadsheet won't actually stop you specifying a meaningless range: it's up to you as a developer to avoid such errors. +When an AutoFilter is applied to a range of cells, the first row in an +autofilter range will be the heading row, which displays the autoFilter +dropdown icons. It is not part of the actual autoFiltered data. All +subsequent rows are the autoFiltered data. So an AutoFilter range should +always contain the heading row and one or more data rows (one data row +is pretty meaningless), but PhpSpreadsheet won't actually stop you +specifying a meaningless range: it's up to you as a developer to avoid +such errors. -To determine if a filter is applied, note the icon in the column heading. A drop-down arrow (![01-03-filter-icon-1.png](./images/01-03-filter-icon-1.png "")) means that filtering is enabled but not applied. In MS Excel, when you hover over the heading of a column with filtering enabled but not applied, a screen tip displays the cell text for the first row in that column, and the message "(Showing All)". +To determine if a filter is applied, note the icon in the column +heading. A drop-down arrow +(![01-03-filter-icon-1.png](./images/01-03-filter-icon-1.png)) means +that filtering is enabled but not applied. In MS Excel, when you hover +over the heading of a column with filtering enabled but not applied, a +screen tip displays the cell text for the first row in that column, and +the message "(Showing All)". -![01-02-autofilter.png](./images/01-02-autofilter.png "") +![01-02-autofilter.png](./images/01-02-autofilter.png) +A Filter button +(![01-03-filter-icon-2.png](./images/01-03-filter-icon-2.png)) means +that a filter is applied. When you hover over the heading of a filtered +column, a screen tip displays the filter that has been applied to that +column, such as "Equals a red cell color" or "Larger than 150". -A Filter button (![01-03-filter-icon-2.png](./images/01-03-filter-icon-2.png "")) means that a filter is applied. When you hover over the heading of a filtered column, a screen tip displays the filter that has been applied to that column, such as "Equals a red cell color" or "Larger than 150". - -![01-04-autofilter.png](./images/01-04-autofilter.png "") - +![01-04-autofilter.png](./images/01-04-autofilter.png) ## Setting an AutoFilter area on a worksheet To set an autoFilter on a range of cells. -```php +``` php $spreadsheet->getActiveSheet()->setAutoFilter('A1:E20'); ``` -The first row in an autofilter range will be the heading row, which displays the autoFilter dropdown icons. It is not part of the actual autoFiltered data. All subsequent rows are the autoFiltered data. So an AutoFilter range should always contain the heading row and one or more data rows (one data row is pretty meaningless, but PhpSpreadsheet won't actually stop you specifying a meaningless range: it's up to you as a developer to avoid such errors. +The first row in an autofilter range will be the heading row, which +displays the autoFilter dropdown icons. It is not part of the actual +autoFiltered data. All subsequent rows are the autoFiltered data. So an +AutoFilter range should always contain the heading row and one or more +data rows (one data row is pretty meaningless, but PhpSpreadsheet won't +actually stop you specifying a meaningless range: it's up to you as a +developer to avoid such errors. If you want to set the whole worksheet as an autofilter region -```php +``` php $spreadsheet->getActiveSheet()->setAutoFilter( $spreadsheet->getActiveSheet() ->calculateWorksheetDimension() @@ -40,52 +65,69 @@ $spreadsheet->getActiveSheet()->setAutoFilter( This enables filtering, but does not actually apply any filters. - ## Autofilter Expressions -PHPEXcel 1.7.8 introduced the ability to actually create, read and write filter expressions; initially only for Xlsx files, but later releases will extend this to other formats. +PHPEXcel 1.7.8 introduced the ability to actually create, read and write +filter expressions; initially only for Xlsx files, but later releases +will extend this to other formats. -To apply a filter expression to an autoFilter range, you first need to identify which column you're going to be applying this filter to. +To apply a filter expression to an autoFilter range, you first need to +identify which column you're going to be applying this filter to. -```php +``` php $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $columnFilter = $autoFilter->getColumn('C'); ``` -This returns an autoFilter column object, and you can then apply filter expressions to that column. +This returns an autoFilter column object, and you can then apply filter +expressions to that column. -There are a number of different types of autofilter expressions. The most commonly used are: +There are a number of different types of autofilter expressions. The +most commonly used are: - - Simple Filters - - DateGroup Filters - - Custom filters - - Dynamic Filters - - Top Ten Filters +- Simple Filters +- DateGroup Filters +- Custom filters +- Dynamic Filters +- Top Ten Filters -These different types are mutually exclusive within any single column. You should not mix the different types of filter in the same column. PhpSpreadsheet will not actively prevent you from doing this, but the results are unpredictable. - -Other filter expression types (such as cell colour filters) are not yet supported. +These different types are mutually exclusive within any single column. +You should not mix the different types of filter in the same column. +PhpSpreadsheet will not actively prevent you from doing this, but the +results are unpredictable. +Other filter expression types (such as cell colour filters) are not yet +supported. ### Simple filters -In MS Excel, Simple Filters are a dropdown list of all values used in that column, and the user can select which ones they want to display and which ones they want to hide by ticking and unticking the checkboxes alongside each option. When the filter is applied, rows containing the checked entries will be displayed, rows that don't contain those values will be hidden. +In MS Excel, Simple Filters are a dropdown list of all values used in +that column, and the user can select which ones they want to display and +which ones they want to hide by ticking and unticking the checkboxes +alongside each option. When the filter is applied, rows containing the +checked entries will be displayed, rows that don't contain those values +will be hidden. -![04-01-simple-autofilter.png](./images/04-01-simple-autofilter.png "") +![04-01-simple-autofilter.png](./images/04-01-simple-autofilter.png) -To create a filter expression, we need to start by identifying the filter type. In this case, we're just going to specify that this filter is a standard filter. +To create a filter expression, we need to start by identifying the +filter type. In this case, we're just going to specify that this filter +is a standard filter. -```php +``` php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER ); ``` -Now we've identified the filter type, we can create a filter rule and set the filter values: +Now we've identified the filter type, we can create a filter rule and +set the filter values: -When creating a simple filter in PhpSpreadsheet, you only need to specify the values for "checked" columns: you do this by creating a filter rule for each value. +When creating a simple filter in PhpSpreadsheet, you only need to +specify the values for "checked" columns: you do this by creating a +filter rule for each value. -```php +``` php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, @@ -99,15 +141,18 @@ $columnFilter->createRule() ); ``` -This creates two filter rules: the column will be filtered by values that match “France” OR “Germany”. For Simple Filters, you can create as many rules as you want +This creates two filter rules: the column will be filtered by values +that match “France” OR “Germany”. For Simple Filters, you can create as +many rules as you want -Simple filters are always a comparison match of EQUALS, and multiple standard filters are always treated as being joined by an OR condition. +Simple filters are always a comparison match of EQUALS, and multiple +standard filters are always treated as being joined by an OR condition. #### Matching Blanks If you want to create a filter to select blank cells, you would use: -```php +``` php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, @@ -117,21 +162,26 @@ $columnFilter->createRule() ### DateGroup Filters -In MS Excel, DateGroup filters provide a series of dropdown filter selectors for date values, so you can specify entire years, or months within a year, or individual days within each month. +In MS Excel, DateGroup filters provide a series of dropdown filter +selectors for date values, so you can specify entire years, or months +within a year, or individual days within each month. -![04-02-dategroup-autofilter.png](./images/04-02-dategroup-autofilter.png "") +![04-02-dategroup-autofilter.png](./images/04-02-dategroup-autofilter.png) DateGroup filters are still applied as a Standard Filter type. -```php +``` php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_FILTER ); ``` -Creating a dateGroup filter in PhpSpreadsheet, you specify the values for "checked" columns as an associative array of year. month, day, hour minute and second. To select a year and month, you need to create a DateGroup rule identifying the selected year and month: +Creating a dateGroup filter in PhpSpreadsheet, you specify the values +for "checked" columns as an associative array of year. month, day, hour +minute and second. To select a year and month, you need to create a +DateGroup rule identifying the selected year and month: -```php +``` php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, @@ -147,31 +197,39 @@ $columnFilter->createRule() The key values for the associative array are: - - year - - month - - day - - hour - - minute - - second +- year +- month +- day +- hour +- minute +- second -Like Standard filters, DateGroup filters are always a match of EQUALS, and multiple standard filters are always treated as being joined by an OR condition. - -Note that we alse specify a ruleType: to differentiate this from a standard filter, we explicitly set the Rule's Type to AUTOFILTER_RULETYPE_DATEGROUP. As with standard filters, we can create any number of DateGroup Filters. +Like Standard filters, DateGroup filters are always a match of EQUALS, +and multiple standard filters are always treated as being joined by an +OR condition. +Note that we alse specify a ruleType: to differentiate this from a +standard filter, we explicitly set the Rule's Type to +AUTOFILTER\_RULETYPE\_DATEGROUP. As with standard filters, we can create +any number of DateGroup Filters. ### Custom filters -In MS Excel, Custom filters allow us to select more complex conditions using an operator as well as a value. Typical examples might be values that fall within a range (e.g. between -20 and +20), or text values with wildcards (e.g. beginning with the letter U). To handle this, they +In MS Excel, Custom filters allow us to select more complex conditions +using an operator as well as a value. Typical examples might be values +that fall within a range (e.g. between -20 and +20), or text values with +wildcards (e.g. beginning with the letter U). To handle this, they -![04-03-custom-autofilter-1.png](./images/04-03-custom-autofilter-1.png "") +![04-03-custom-autofilter-1.png](./images/04-03-custom-autofilter-1.png) -![04-03-custom-autofilter-2.png](./images/04-03-custom-autofilter-2.png "") +![04-03-custom-autofilter-2.png](./images/04-03-custom-autofilter-2.png) -Custom filters are limited to 2 rules, and these can be joined using either an AND or an OR. +Custom filters are limited to 2 rules, and these can be joined using +either an AND or an OR. We start by specifying a Filter type, this time a CUSTOMFILTER. -```php +``` php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER ); @@ -179,9 +237,10 @@ $columnFilter->setFilterType( And then define our rules. -The following shows a simple wildcard filter to show all column entries beginning with the letter 'U'. +The following shows a simple wildcard filter to show all column entries +beginning with the letter 'U'. -```php +``` php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, @@ -192,13 +251,20 @@ $columnFilter->createRule() ); ``` -MS Excel uses \* as a wildcard to match any number of characters, and ? as a wildcard to match a single character. 'U\*' equates to "begins with a 'U'"; '\*U' equates to "ends with a 'U'"; and '\*U\*' equates to "contains a 'U'" +MS Excel uses \* as a wildcard to match any number of characters, and ? +as a wildcard to match a single character. 'U\*' equates to "begins with +a 'U'"; '\*U' equates to "ends with a 'U'"; and '\*U\*' equates to +"contains a 'U'" -If you want to match explicitly against a \* or a ? character, you can escape it with a tilde (~), so ?~\*\* would explicitly match for a \* character as the second character in the cell value, followed by any number of other characters. The only other character that needs escaping is the ~ itself. +If you want to match explicitly against a \* or a ? character, you can +escape it with a tilde (\~), so ?\~\*\* would explicitly match for a \* +character as the second character in the cell value, followed by any +number of other characters. The only other character that needs escaping +is the \~ itself. To create a "between" condition, we need to define two rules: -```php +``` php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, @@ -219,15 +285,19 @@ $columnFilter->createRule() We also set the rule type to CUSTOMFILTER. -This defined two rules, filtering numbers that are >= -20 OR <= 20, so we also need to modify the join condition to reflect AND rather than OR. +This defined two rules, filtering numbers that are >= -20 OR <= +20, so we also need to modify the join condition to reflect AND rather +than OR. -```php +``` php $columnFilter->setAndOr( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_COLUMN_ANDOR_AND ); ``` -The valid set of operators for Custom Filters are defined in the \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule class, and comprise: +The valid set of operators for Custom Filters are defined in the +\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule class, and +comprise: Operator Constant | Value ------------------------------------------|---------------------- @@ -238,24 +308,29 @@ AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL | 'greaterThanOrEqual' AUTOFILTER_COLUMN_RULE_LESSTHAN | 'lessThan' AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL | 'lessThanOrEqual' - ### Dynamic Filters -Dynamic Filters are based on a dynamic comparison condition, where the value we're comparing against the cell values is variable, such as 'today'; or when we're testing against an aggregate of the cell data (e.g. 'aboveAverage'). Only a single dynamic filter can be applied to a column at a time. +Dynamic Filters are based on a dynamic comparison condition, where the +value we're comparing against the cell values is variable, such as +'today'; or when we're testing against an aggregate of the cell data +(e.g. 'aboveAverage'). Only a single dynamic filter can be applied to a +column at a time. -![04-04-dynamic-autofilter.png](./images/04-04-dynamic-autofilter.png "") +![04-04-dynamic-autofilter.png](./images/04-04-dynamic-autofilter.png) Again, we start by specifying a Filter type, this time a DYNAMICFILTER. -```php +``` php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER ); ``` -When defining the rule for a dynamic filter, we don't define a value (we can simply set that to NULL) but we do specify the dynamic filter category. +When defining the rule for a dynamic filter, we don't define a value (we +can simply set that to NULL) but we do specify the dynamic filter +category. -```php +``` php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL, @@ -269,7 +344,9 @@ $columnFilter->createRule() We also set the rule type to DYNAMICFILTER. -The valid set of dynamic filter categories is defined in the \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule class, and comprises: +The valid set of dynamic filter categories is defined in the +\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule class, and +comprises: Operator Constant | Value -----------------------------------------|---------------- @@ -322,22 +399,28 @@ AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE | 'belowAverage' We can only apply a single Dynamic Filter rule to a column at a time. - ### Top Ten Filters -Top Ten Filters are similar to Dynamic Filters in that they are based on a summarisation of the actual data values in the cells. However, unlike Dynamic Filters where you can only select a single option, Top Ten Filters allow you to select based on a number of criteria: +Top Ten Filters are similar to Dynamic Filters in that they are based on +a summarisation of the actual data values in the cells. However, unlike +Dynamic Filters where you can only select a single option, Top Ten +Filters allow you to select based on a number of criteria: -![04-05-custom-topten-1.png](./images/04-05-topten-autofilter-1.png "") +![04-05-custom-topten-1.png](./images/04-05-topten-autofilter-1.png) -![04-05-custom-topten-2.png](./images/04-05-topten-autofilter-2.png "") +![04-05-custom-topten-2.png](./images/04-05-topten-autofilter-2.png) -You can identify whether you want the top (highest) or bottom (lowest) values.You can identify how many values you wish to select in the filterYou can identify whether this should be a percentage or a number of items. +You can identify whether you want the top (highest) or bottom (lowest) +values.You can identify how many values you wish to select in the +filterYou can identify whether this should be a percentage or a number +of items. -Like Dynamic Filters, only a single Top Ten filter can be applied to a column at a time. +Like Dynamic Filters, only a single Top Ten filter can be applied to a +column at a time. We start by specifying a Filter type, this time a DYNAMICFILTER. -```php +``` php $columnFilter->setFilterType( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER ); @@ -345,7 +428,7 @@ $columnFilter->setFilterType( Then we create the rule: -```php +``` php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, @@ -361,7 +444,7 @@ This will filter the Top 5 percent of values in the column. To specify the lowest (bottom 2 values), we would specify a rule of: -```php +``` php $columnFilter->createRule() ->setRule( \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, @@ -373,7 +456,10 @@ $columnFilter->createRule() ); ``` -The option values for TopTen Filters top/bottom value/percent are all defined in the \PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule class, and comprise: +The option values for TopTen Filters top/bottom value/percent are all +defined in the +\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule class, and +comprise: Operator Constant | Value ---------------------------------------|------------- @@ -389,26 +475,37 @@ AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM | 'bottom' ## Executing an AutoFilter -When an autofilter is applied in MS Excel, it sets the row hidden/visible flags for each row of the autofilter area based on the selected criteria, so that only those rows that match the filter criteria are displayed. +When an autofilter is applied in MS Excel, it sets the row +hidden/visible flags for each row of the autofilter area based on the +selected criteria, so that only those rows that match the filter +criteria are displayed. -PhpSpreadsheet will not execute the equivalent function automatically when you set or change a filter expression, but only when the file is saved. +PhpSpreadsheet will not execute the equivalent function automatically +when you set or change a filter expression, but only when the file is +saved. ### Applying the Filter -If you wish to execute your filter from within a script, you need to do this manually. You can do this using the autofilters showHideRows() method. +If you wish to execute your filter from within a script, you need to do +this manually. You can do this using the autofilters showHideRows() +method. -```php +``` php $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $autoFilter->showHideRows(); ``` -This will set all rows that match the filter criteria to visible, while hiding all other rows within the autofilter area. +This will set all rows that match the filter criteria to visible, while +hiding all other rows within the autofilter area. ### Displaying Filtered Rows -Simply looping through the rows in an autofilter area will still access ever row, whether it matches the filter criteria or not. To selectively access only the filtered rows, you need to test each row’s visibility settings. +Simply looping through the rows in an autofilter area will still access +ever row, whether it matches the filter criteria or not. To selectively +access only the filtered rows, you need to test each row’s visibility +settings. -```php +``` php foreach ($spreadsheet->getActiveSheet()->getRowIterator() as $row) { if ($spreadsheet->getActiveSheet() ->getRowDimension($row->getRowIndex())->getVisible()) { @@ -429,5 +526,5 @@ foreach ($spreadsheet->getActiveSheet()->getRowIterator() as $row) { ## AutoFilter Sorting -In MS Excel, Autofiltering also allows the rows to be sorted. This feature is ***not*** supported by PhpSpreadsheet. - +In MS Excel, Autofiltering also allows the rows to be sorted. This +feature is ***not*** supported by PhpSpreadsheet. diff --git a/docs/topics/calculation-engine.md b/docs/topics/calculation-engine.md index f97d40d0..650e0847 100644 --- a/docs/topics/calculation-engine.md +++ b/docs/topics/calculation-engine.md @@ -4,177 +4,267 @@ ### Performing formula calculations -As PhpSpreadsheet represents an in-memory spreadsheet, it also offers formula calculation capabilities. A cell can be of a value type (containing a number or text), or a formula type (containing a formula which can be evaluated). For example, the formula "=SUM(A1:A10)" evaluates to the sum of values in A1, A2, ..., A10. +As PhpSpreadsheet represents an in-memory spreadsheet, it also offers +formula calculation capabilities. A cell can be of a value type +(containing a number or text), or a formula type (containing a formula +which can be evaluated). For example, the formula "=SUM(A1:A10)" +evaluates to the sum of values in A1, A2, ..., A10. -To calculate a formula, you can call the cell containing the formula’s method getCalculatedValue(), for example: +To calculate a formula, you can call the cell containing the formula’s +method getCalculatedValue(), for example: -```php +``` php $spreadsheet->getActiveSheet()->getCell('E11')->getCalculatedValue(); ``` -If you write the following line of code in the invoice demo included with PhpSpreadsheet, it evaluates to the value "64": -![09-command-line-calculation.png](./images/09-command-line-calculation.png "") +If you write the following line of code in the invoice demo included +with PhpSpreadsheet, it evaluates to the value "64": -Another nice feature of PhpSpreadsheet's formula parser, is that it can automatically adjust a formula when inserting/removing rows/columns. Here's an example: +![09-command-line-calculation.png](./images/09-command-line-calculation.png) -![09-formula-in-cell-1.png](./images/09-formula-in-cell-1.png "") +Another nice feature of PhpSpreadsheet's formula parser, is that it can +automatically adjust a formula when inserting/removing rows/columns. +Here's an example: -You see that the formula contained in cell E11 is "SUM(E4:E9)". Now, when I write the following line of code, two new product lines are added: +![09-formula-in-cell-1.png](./images/09-formula-in-cell-1.png) -```php +You see that the formula contained in cell E11 is "SUM(E4:E9)". Now, +when I write the following line of code, two new product lines are +added: + +``` php $spreadsheet->getActiveSheet()->insertNewRowBefore(7, 2); ``` -![09-formula-in-cell-2.png](./images/09-formula-in-cell-2.png "") +![09-formula-in-cell-2.png](./images/09-formula-in-cell-2.png) -Did you notice? The formula in the former cell E11 (now E13, as I inserted 2 new rows), changed to "SUM(E4:E11)". Also, the inserted cells duplicate style information of the previous cell, just like Excel's behaviour. Note that you can both insert rows and columns. +Did you notice? The formula in the former cell E11 (now E13, as I +inserted 2 new rows), changed to "SUM(E4:E11)". Also, the inserted cells +duplicate style information of the previous cell, just like Excel's +behaviour. Note that you can both insert rows and columns. ## Known limitations -There are some known limitations to the PhpSpreadsheet calculation engine. Most of them are due to the fact that an Excel formula is converted into PHP code before being executed. This means that Excel formula calculation is subject to PHP's language characteristics. +There are some known limitations to the PhpSpreadsheet calculation +engine. Most of them are due to the fact that an Excel formula is +converted into PHP code before being executed. This means that Excel +formula calculation is subject to PHP's language characteristics. ### Function that are not Supported in Xls -Not all functions are supported, for a comprehensive list, read the [function list by name](../references/function-list-by-name.md). +Not all functions are supported, for a comprehensive list, read the +[function list by name](../references/function-list-by-name.md). #### Operator precedence -In Excel '+' wins over '&', just like '*' wins over '+' in ordinary algebra. The former rule is not what one finds using the calculation engine shipped with PhpSpreadsheet. +In Excel '+' wins over '&', just like '\*' wins over '+' in ordinary +algebra. The former rule is not what one finds using the calculation +engine shipped with PhpSpreadsheet. -Reference for operator precedence in Excel: [http://support.microsoft.com/kb/25189](http://support.microsoft.com/kb/25189) +Reference for operator precedence in Excel: + -Reference for operator precedence in PHP: [http://www.php.net/operators](http://www.php.net/operators) +Reference for operator precedence in PHP: #### Formulas involving numbers and text -Formulas involving numbers and text may produce unexpected results or even unreadable file contents. For example, the formula '=3+"Hello "' is expected to produce an error in Excel (#VALUE!). Due to the fact that PHP converts “Hello” to a numeric value (zero), the result of this formula is evaluated as 3 instead of evaluating as an error. This also causes the Excel document being generated as containing unreadable content. +Formulas involving numbers and text may produce unexpected results or +even unreadable file contents. For example, the formula '=3+"Hello "' is +expected to produce an error in Excel (\#VALUE!). Due to the fact that +PHP converts “Hello” to a numeric value (zero), the result of this +formula is evaluated as 3 instead of evaluating as an error. This also +causes the Excel document being generated as containing unreadable +content. -Reference for this behaviour in PHP: [http://php.net/manual/en/language.types.string.php#language.types.string.conversion](http://php.net/manual/en/language.types.string.php#language.types.string.conversion) +Reference for this behaviour in PHP: + #### Formulas don’t seem to be calculated in Excel2003 using compatibility pack? -This is normal behaviour of the compatibility pack, Xlsx displays this correctly. Use \PhpOffice\PhpSpreadsheet\Writer\Xls if you really need calculated values, or force recalculation in Excel2003. - +This is normal behaviour of the compatibility pack, Xlsx displays this +correctly. Use \PhpOffice\PhpSpreadsheet\Writer\Xls if you really need +calculated values, or force recalculation in Excel2003. ## Handling Date and Time Values ### Excel functions that return a Date and Time value -Any of the Date and Time functions that return a date value in Excel can return either an Excel timestamp or a PHP timestamp or date object. +Any of the Date and Time functions that return a date value in Excel can +return either an Excel timestamp or a PHP timestamp or date object. -It is possible for scripts to change the data type used for returning date values by calling the \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType() method: +It is possible for scripts to change the data type used for returning +date values by calling the +\PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType() +method: -```php +``` php \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType($returnDateType); ``` -where the following constants can be used for $returnDateType +where the following constants can be used for \$returnDateType - - `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_NUMERIC` - - `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_OBJECT` - - `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL` +- `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_NUMERIC` +- `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_PHP_OBJECT` +- `\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL` -The method will return a Boolean True on success, False on failure (e.g. if an invalid value is passed in for the return date type). +The method will return a Boolean True on success, False on failure (e.g. +if an invalid value is passed in for the return date type). -The \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType() method can be used to determine the current value of this setting: +The \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType() +method can be used to determine the current value of this setting: -```php +``` php $returnDateType = \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(); ``` -The default is RETURNDATE_PHP_NUMERIC. +The default is RETURNDATE\_PHP\_NUMERIC. #### PHP Timestamps -If RETURNDATE_PHP_NUMERIC is set for the Return Date Type, then any date value returned to the calling script by any access to the Date and Time functions in Excel will be an integer value that represents the number of seconds from the PHP/Unix base date. The PHP/Unix base date (0) is 00:00 UST on 1st January 1970. This value can be positive or negative: so a value of -3600 would be 23:00 hrs on 31st December 1969; while a value of +3600 would be 01:00 hrs on 1st January 1970. This gives PHP a date range of between 14th December 1901 and 19th January 2038. +If RETURNDATE\_PHP\_NUMERIC is set for the Return Date Type, then any +date value returned to the calling script by any access to the Date and +Time functions in Excel will be an integer value that represents the +number of seconds from the PHP/Unix base date. The PHP/Unix base date +(0) is 00:00 UST on 1st January 1970. This value can be positive or +negative: so a value of -3600 would be 23:00 hrs on 31st December 1969; +while a value of +3600 would be 01:00 hrs on 1st January 1970. This +gives PHP a date range of between 14th December 1901 and 19th January +2038. #### PHP DateTime Objects -If the Return Date Type is set for RETURNDATE_PHP_NUMERIC, then any date value returned to the calling script by any access to the Date and Time functions in Excel will be a PHP date/time object. +If the Return Date Type is set for RETURNDATE\_PHP\_NUMERIC, then any +date value returned to the calling script by any access to the Date and +Time functions in Excel will be a PHP date/time object. #### Excel Timestamps -If RETURNDATE_EXCEL is set for the Return Date Type, then the returned date value by any access to the Date and Time functions in Excel will be a floating point value that represents a number of days from the Excel base date. The Excel base date is determined by which calendar Excel uses: the Windows 1900 or the Mac 1904 calendar. 1st January 1900 is the base date for the Windows 1900 calendar while 1st January 1904 is the base date for the Mac 1904 calendar. +If RETURNDATE\_EXCEL is set for the Return Date Type, then the returned +date value by any access to the Date and Time functions in Excel will be +a floating point value that represents a number of days from the Excel +base date. The Excel base date is determined by which calendar Excel +uses: the Windows 1900 or the Mac 1904 calendar. 1st January 1900 is the +base date for the Windows 1900 calendar while 1st January 1904 is the +base date for the Mac 1904 calendar. -It is possible for scripts to change the calendar used for calculating Excel date values by calling the \PhpOffice\PhpSpreadsheet\Shared\Date::setExcelCalendar() method: +It is possible for scripts to change the calendar used for calculating +Excel date values by calling the +\PhpOffice\PhpSpreadsheet\Shared\Date::setExcelCalendar() method: -```php +``` php \PhpOffice\PhpSpreadsheet\Shared\Date::setExcelCalendar($baseDate); ``` -where the following constants can be used for $baseDate +where the following constants can be used for \$baseDate - - \PhpOffice\PhpSpreadsheet\Shared\Date::CALENDAR_WINDOWS_1900 - - \PhpOffice\PhpSpreadsheet\Shared\Date::CALENDAR_MAC_1904 +- \PhpOffice\PhpSpreadsheet\Shared\Date::CALENDAR\_WINDOWS\_1900 +- \PhpOffice\PhpSpreadsheet\Shared\Date::CALENDAR\_MAC\_1904 -The method will return a Boolean True on success, False on failure (e.g. if an invalid value is passed in). +The method will return a Boolean True on success, False on failure (e.g. +if an invalid value is passed in). -The \PhpOffice\PhpSpreadsheet\Shared\Date::getExcelCalendar() method can be used to determine the current value of this setting: +The \PhpOffice\PhpSpreadsheet\Shared\Date::getExcelCalendar() method can +be used to determine the current value of this setting: -```php +``` php $baseDate = \PhpOffice\PhpSpreadsheet\Shared\Date::getExcelCalendar(); ``` -The default is CALENDAR_WINDOWS_1900. + +The default is CALENDAR\_WINDOWS\_1900. #### Functions that return a Date/Time Value - - DATE - - DATEVALUE - - EDATE - - EOMONTH - - NOW - - TIME - - TIMEVALUE - - TODAY +- DATE +- DATEVALUE +- EDATE +- EOMONTH +- NOW +- TIME +- TIMEVALUE +- TODAY ### Excel functions that accept Date and Time values as parameters -Date values passed in as parameters to a function can be an Excel timestamp or a PHP timestamp; or date object; or a string containing a date value (e.g. '1-Jan-2009'). PhpSpreadsheet will attempt to identify their type based on the PHP datatype: +Date values passed in as parameters to a function can be an Excel +timestamp or a PHP timestamp; or date object; or a string containing a +date value (e.g. '1-Jan-2009'). PhpSpreadsheet will attempt to identify +their type based on the PHP datatype: -An integer numeric value will be treated as a PHP/Unix timestamp. A real (floating point) numeric value will be treated as an Excel date/timestamp. Any PHP DateTime object will be treated as a DateTime object. Any string value (even one containing straight numeric data) will be converted to a date/time object for validation as a date value based on the server locale settings, so passing through an ambiguous value of '07/08/2008' will be treated as 7th August 2008 if your server settings are UK, but as 8th July 2008 if your server settings are US. However, if you pass through a value such as '31/12/2008' that would be considered an error by a US-based server, but which is not ambiguous, then PhpSpreadsheet will attempt to correct this to 31st December 2008. If the content of the string doesn’t match any of the formats recognised by the php date/time object implementation of strtotime() (which can handle a wider range of formats than the normal strtotime() function), then the function will return a '#VALUE' error. However, Excel recommends that you should always use date/timestamps for your date functions, and the recommendation for PhpSpreadsheet is the same: avoid strings because the result is not predictable. +An integer numeric value will be treated as a PHP/Unix timestamp. A real +(floating point) numeric value will be treated as an Excel +date/timestamp. Any PHP DateTime object will be treated as a DateTime +object. Any string value (even one containing straight numeric data) +will be converted to a date/time object for validation as a date value +based on the server locale settings, so passing through an ambiguous +value of '07/08/2008' will be treated as 7th August 2008 if your server +settings are UK, but as 8th July 2008 if your server settings are US. +However, if you pass through a value such as '31/12/2008' that would be +considered an error by a US-based server, but which is not ambiguous, +then PhpSpreadsheet will attempt to correct this to 31st December 2008. +If the content of the string doesn’t match any of the formats recognised +by the php date/time object implementation of strtotime() (which can +handle a wider range of formats than the normal strtotime() function), +then the function will return a '\#VALUE' error. However, Excel +recommends that you should always use date/timestamps for your date +functions, and the recommendation for PhpSpreadsheet is the same: avoid +strings because the result is not predictable. -The same principle applies when data is being written to Excel. Cells containing date actual values (rather than Excel functions that return a date value) are always written as Excel dates, converting where necessary. If a cell formatted as a date contains an integer or date/time object value, then it is converted to an Excel value for writing: if a cell formatted as a date contains a real value, then no conversion is required. Note that string values are written as strings rather than converted to Excel date timestamp values. +The same principle applies when data is being written to Excel. Cells +containing date actual values (rather than Excel functions that return a +date value) are always written as Excel dates, converting where +necessary. If a cell formatted as a date contains an integer or +date/time object value, then it is converted to an Excel value for +writing: if a cell formatted as a date contains a real value, then no +conversion is required. Note that string values are written as strings +rather than converted to Excel date timestamp values. #### Functions that expect a Date/Time Value - - DATEDIF - - DAY - - DAYS360 - - EDATE - - EOMONTH - - HOUR - - MINUTE - - MONTH - - NETWORKDAYS - - SECOND - - WEEKDAY - - WEEKNUM - - WORKDAY - - YEAR - - YEARFRAC +- DATEDIF +- DAY +- DAYS360 +- EDATE +- EOMONTH +- HOUR +- MINUTE +- MONTH +- NETWORKDAYS +- SECOND +- WEEKDAY +- WEEKNUM +- WORKDAY +- YEAR +- YEARFRAC ### Helper Methods -In addition to the setExcelCalendar() and getExcelCalendar() methods, a number of other methods are available in the \PhpOffice\PhpSpreadsheet\Shared\Date class that can help when working with dates: +In addition to the setExcelCalendar() and getExcelCalendar() methods, a +number of other methods are available in the +\PhpOffice\PhpSpreadsheet\Shared\Date class that can help when working +with dates: -#### \PhpOffice\PhpSpreadsheet\Shared\Date::ExcelToPHP($excelDate) +#### \PhpOffice\PhpSpreadsheet\Shared\Date::ExcelToPHP(\$excelDate) -Converts a date/time from an Excel date timestamp to return a PHP serialized date/timestamp. +Converts a date/time from an Excel date timestamp to return a PHP +serialized date/timestamp. -Note that this method does not trap for Excel dates that fall outside of the valid range for a PHP date timestamp. +Note that this method does not trap for Excel dates that fall outside of +the valid range for a PHP date timestamp. -#### \PhpOffice\PhpSpreadsheet\Shared\Date::ExcelToPHPObject($excelDate) +#### \PhpOffice\PhpSpreadsheet\Shared\Date::ExcelToPHPObject(\$excelDate) -Converts a date from an Excel date/timestamp to return a PHP DateTime object. +Converts a date from an Excel date/timestamp to return a PHP DateTime +object. -#### \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($PHPDate) +#### \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel(\$PHPDate) -Converts a PHP serialized date/timestamp or a PHP DateTime object to return an Excel date timestamp. +Converts a PHP serialized date/timestamp or a PHP DateTime object to +return an Excel date timestamp. -#### \PhpOffice\PhpSpreadsheet\Shared\Date::FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) - -Takes year, month and day values (and optional hour, minute and second values) and returns an Excel date timestamp value. +#### \PhpOffice\PhpSpreadsheet\Shared\Date::FormattedPHPToExcel(\$year, \$month, \$day, \$hours=0, \$minutes=0, \$seconds=0) +Takes year, month and day values (and optional hour, minute and second +values) and returns an Excel date timestamp value. ## Function Reference @@ -182,27 +272,35 @@ Takes year, month and day values (and optional hour, minute and second values) a #### DAVERAGE -The DAVERAGE function returns the average value of the cells in a column of a list or database that match conditions you specify. +The DAVERAGE function returns the average value of the cells in a column +of a list or database that match conditions you specify. ##### Syntax -``` -DAVERAGE (database, field, criteria) -``` + DAVERAGE (database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -212,7 +310,7 @@ This is the statistical mean. ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -244,35 +342,43 @@ There are no additional notes on this function #### DCOUNT -The DCOUNT function returns the count of cells that contain a number in a column of a list or database matching conditions that you specify. +The DCOUNT function returns the count of cells that contain a number in +a column of a list or database matching conditions that you specify. ##### Syntax -``` -DCOUNT(database, [field], criteria) -``` + DCOUNT(database, [field], criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value -**float** The count of the matching cells. +**float** The count of the matching cells. ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -301,31 +407,41 @@ $retVal = $worksheet->getCell('A12')->getCalculatedValue(); ##### Notes -In MS Excel, The field argument is optional. If field is omitted, DCOUNT counts all records in the database that match the criteria. This logic has not yet been implemented in PhpSpreadsheet. +In MS Excel, The field argument is optional. If field is omitted, DCOUNT +counts all records in the database that match the criteria. This logic +has not yet been implemented in PhpSpreadsheet. #### DCOUNTA -The DCOUNT function returns the count of cells that aren’t blank in a column of a list or database and that match conditions that you specify. +The DCOUNT function returns the count of cells that aren’t blank in a +column of a list or database and that match conditions that you specify. ##### Syntax -``` -DCOUNTA(database, [field], criteria) -``` + DCOUNTA(database, [field], criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -333,7 +449,7 @@ You can use any range for the criteria argument, as long as it includes at least ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -362,31 +478,41 @@ $retVal = $worksheet->getCell('A12')->getCalculatedValue(); ##### Notes -In MS Excel, The field argument is optional. If field is omitted, DCOUNTA counts all records in the database that match the criteria. This logic has not yet been implemented in PhpSpreadsheet. +In MS Excel, The field argument is optional. If field is omitted, +DCOUNTA counts all records in the database that match the criteria. This +logic has not yet been implemented in PhpSpreadsheet. #### DGET -The DGET function extracts a single value from a column of a list or database that matches conditions that you specify. +The DGET function extracts a single value from a column of a list or +database that matches conditions that you specify. ##### Syntax -``` -DGET(database, field, criteria) -``` + DGET(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -394,7 +520,7 @@ You can use any range for the criteria argument, as long as it includes at least #### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -426,27 +552,35 @@ There are no additional notes on this function #### DMAX -The DMAX function returns the largest number in a column of a list or database that matches conditions you specify. +The DMAX function returns the largest number in a column of a list or +database that matches conditions you specify. ##### Syntax -``` -DMAX(database, field, criteria) -``` + DMAX(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -454,7 +588,7 @@ You can use any range for the criteria argument, as long as it includes at least ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -486,27 +620,35 @@ There are no additional notes on this function #### DMIN -The DMIN function returns the smallest number in a column of a list or database that matches conditions you specify. +The DMIN function returns the smallest number in a column of a list or +database that matches conditions you specify. ##### Syntax -``` -DMIN(database, field, criteria) -``` + DMIN(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -514,7 +656,7 @@ You can use any range for the criteria argument, as long as it includes at least ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -546,27 +688,35 @@ There are no additional notes on this function #### DPRODUCT -The DPRODUCT function multiplies the values in a column of a list or database that match conditions that you specify. +The DPRODUCT function multiplies the values in a column of a list or +database that match conditions that you specify. ##### Syntax -``` -DPRODUCT(database, field, criteria) -``` + DPRODUCT(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -574,7 +724,7 @@ You can use any range for the criteria argument, as long as it includes at least ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -606,27 +756,36 @@ There are no additional notes on this function #### DSTDEV -The DSTDEV function estimates the standard deviation of a population based on a sample by using the numbers in a column of a list or database that match conditions that you specify. +The DSTDEV function estimates the standard deviation of a population +based on a sample by using the numbers in a column of a list or database +that match conditions that you specify. ##### Syntax -``` -DSTDEV(database, field, criteria) -``` + DSTDEV(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -634,7 +793,7 @@ You can use any range for the criteria argument, as long as it includes at least ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -666,27 +825,36 @@ There are no additional notes on this function #### DSTDEVP -The DSTDEVP function calculates the standard deviation of a population based on the entire population by using the numbers in a column of a list or database that match conditions that you specify. +The DSTDEVP function calculates the standard deviation of a population +based on the entire population by using the numbers in a column of a +list or database that match conditions that you specify. ##### Syntax -``` -DSTDEVP(database, field, criteria) -``` + DSTDEVP(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -694,7 +862,7 @@ You can use any range for the criteria argument, as long as it includes at least ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -726,27 +894,35 @@ There are no additional notes on this function #### DSUM -The DSUM function adds the numbers in a column of a list or database that matches conditions you specify. +The DSUM function adds the numbers in a column of a list or database +that matches conditions you specify. ##### Syntax -``` -DSUM(database, field, criteria) -``` + DSUM(database, field, criteria) ##### Parameters **database** The range of cells that makes up the list or database. -A database is a list of related data in which rows of related information are records, and columns of data are fields. The first row of the list contains labels for each column. +A database is a list of related data in which rows of related +information are records, and columns of data are fields. The first row +of the list contains labels for each column. -**field** Indicates which column of the database is used in the function. +**field** Indicates which column of the database is used in the +function. -Enter the column label as a string (enclosed between double quotation marks), such as "Age" or "Yield," or as a number (without quotation marks) that represents the position of the column within the list: 1 for the first column, 2 for the second column, and so on. +Enter the column label as a string (enclosed between double quotation +marks), such as "Age" or "Yield," or as a number (without quotation +marks) that represents the position of the column within the list: 1 for +the first column, 2 for the second column, and so on. -**criteria** The range of cells that contains the conditions you specify. +**criteria** The range of cells that contains the conditions you +specify. -You can use any range for the criteria argument, as long as it includes at least one column label and at least one cell below the column label in which you specify a condition for the column. +You can use any range for the criteria argument, as long as it includes +at least one column label and at least one cell below the column label +in which you specify a condition for the column. ##### Return Value @@ -754,7 +930,7 @@ You can use any range for the criteria argument, as long as it includes at least ##### Examples -```php +``` php $database = array( array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ), array( 'Apple', 18, 20, 14, 105.00 ), @@ -792,49 +968,70 @@ Not yet documented. Not yet documented. - - ### Date and Time Functions -Excel provides a number of functions for the manipulation of dates and times, and calculations based on date/time values. it is worth spending some time reading the section titled "Date and Time Values" on passing date parameters and returning date values to understand how PhpSpreadsheet reconciles the differences between dates and times in Excel and in PHP. +Excel provides a number of functions for the manipulation of dates and +times, and calculations based on date/time values. it is worth spending +some time reading the section titled "Date and Time Values" on passing +date parameters and returning date values to understand how +PhpSpreadsheet reconciles the differences between dates and times in +Excel and in PHP. #### DATE -The DATE function returns an Excel timestamp or a PHP timestamp or date object representing the date that is referenced by the parameters. +The DATE function returns an Excel timestamp or a PHP timestamp or date +object representing the date that is referenced by the parameters. ##### Syntax -``` -DATE(year, month, day) -``` + DATE(year, month, day) ##### Parameters **year** The year number. -If this value is between 0 (zero) and 1899 inclusive (for the Windows 1900 calendar), or between 4 and 1903 inclusive (for the Mac 1904), then PhpSpreadsheet adds it to the Calendar base year, so a value of 108 will interpret the year as 2008 when using the Windows 1900 calendar, or 2012 when using the Mac 1904 calendar. +If this value is between 0 (zero) and 1899 inclusive (for the Windows +1900 calendar), or between 4 and 1903 inclusive (for the Mac 1904), then +PhpSpreadsheet adds it to the Calendar base year, so a value of 108 will +interpret the year as 2008 when using the Windows 1900 calendar, or 2012 +when using the Mac 1904 calendar. **month** The month number. -If this value is greater than 12, the DATE function adds that number of months to the first month in the year specified. For example, DATE(2008,14,2) returns a value representing February 2, 2009. +If this value is greater than 12, the DATE function adds that number of +months to the first month in the year specified. For example, +DATE(2008,14,2) returns a value representing February 2, 2009. -If the value of __month__ is less than 1, then that value will be adjusted by -1, and that will then be subtracted from the first month of the year specified. For example, DATE(2008,0,2) returns a value representing December 2, 2007; while DATE(2008,-1,2) returns a value representing November 2, 2007. +If the value of **month** is less than 1, then that value will be +adjusted by -1, and that will then be subtracted from the first month of +the year specified. For example, DATE(2008,0,2) returns a value +representing December 2, 2007; while DATE(2008,-1,2) returns a value +representing November 2, 2007. **day** The day number. -If this value is greater than the number of days in the month (and year) specified, the DATE function adds that number of days to the first day in the month. For example, DATE(2008,1,35) returns a value representing February 4, 2008. +If this value is greater than the number of days in the month (and year) +specified, the DATE function adds that number of days to the first day +in the month. For example, DATE(2008,1,35) returns a value representing +February 4, 2008. -If the value of __day__ is less than 1, then that value will be adjusted by -1, and that will then be subtracted from the first month of the year specified. For example, DATE(2008,3,0) returns a value representing February 29, 2008; while DATE(2008,3,-2) returns a value representing February 27, 2008. +If the value of **day** is less than 1, then that value will be adjusted +by -1, and that will then be subtracted from the first month of the year +specified. For example, DATE(2008,3,0) returns a value representing +February 29, 2008; while DATE(2008,3,-2) returns a value representing +February 27, 2008. ##### Return Value **mixed** A date/time stamp that corresponds to the given date. -This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). +This could be a PHP timestamp value (integer), a PHP date/time object, +or an Excel timestamp value (real), depending on the value of +\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Year') ->setCellValue('A2', 'Month') ->setCellValue('A3', 'Day'); @@ -849,7 +1046,7 @@ $retVal = $worksheet->getCell('D1')->getCalculatedValue(); // $retVal = 1230681600 ``` -```php +``` php // We're going to be calling the same cell calculation multiple times, // and expecting different return values, so disable calculation cacheing \PhpOffice\PhpSpreadsheet\Calculation::getInstance()->setCalculationCacheEnabled(FALSE); @@ -885,23 +1082,24 @@ There are no additional notes on this function #### DATEDIF -The DATEDIF function computes the difference between two dates in a variety of different intervals, such number of years, months, or days. +The DATEDIF function computes the difference between two dates in a +variety of different intervals, such number of years, months, or days. ##### Syntax -``` -DATEDIF(date1, date2 [, unit]) -``` + DATEDIF(date1, date2 [, unit]) ##### Parameters **date1** First Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **date2** Second Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **unit** The interval type to use for the calculation @@ -920,13 +1118,16 @@ The unit value is not case sensitive, and defaults to "d". ##### Return Value -**integer** An integer value that reflects the difference between the two dates. +**integer** An integer value that reflects the difference between the +two dates. -This could be the number of full days, months or years between the two dates, depending on the interval unit value passed into the function as the third parameter. +This could be the number of full days, months or years between the two +dates, depending on the interval unit value passed into the function as +the third parameter. ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Year') ->setCellValue('A2', 'Month') ->setCellValue('A3', 'Day'); @@ -964,7 +1165,7 @@ $retVal = $worksheet->getCell('D6')->getCalculatedValue(); // $retVal = 30 ``` -```php +``` php $date1 = 1193317015; // PHP timestamp for 25-Oct-2007 $date2 = 1449579415; // PHP timestamp for 8-Dec-2015 @@ -1007,17 +1208,17 @@ $retVal = call_user_func_array( ##### Notes -If Date1 is later than Date2, DATEDIF will return a #NUM! error. +If Date1 is later than Date2, DATEDIF will return a \#NUM! error. #### DATEVALUE -The DATEVALUE function returns the date represented by a date formatted as a text string. Use DATEVALUE to convert a date represented by text to a serial number. +The DATEVALUE function returns the date represented by a date formatted +as a text string. Use DATEVALUE to convert a date represented by text to +a serial number. ##### Syntax -``` -DATEVALUE(dateString) -``` + DATEVALUE(dateString) ##### Parameters @@ -1029,11 +1230,13 @@ A string, representing a date value. **mixed** A date/time stamp that corresponds to the given date. -This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). +This could be a PHP timestamp value (integer), a PHP date/time object, +or an Excel timestamp value (real), depending on the value of +\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Date String'); ->setCellValue('A2', '31-Dec-2008') ->setCellValue('A3', '31/12/2008') @@ -1055,7 +1258,7 @@ $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 39813.0 for all cases ``` -```php +``` php // We're going to be calling the same cell calculation multiple times, // and expecting different return values, so disable calculation cacheing \PhpOffice\PhpSpreadsheet\Calculation::getInstance()->setCalculationCacheEnabled(FALSE); @@ -1087,27 +1290,35 @@ $retVal = call_user_func_array( ##### Notes -DATEVALUE uses the php date/time object implementation of strtotime() (which can handle a wider range of formats than the normal strtotime() function), and it is also called for any date parameter passed to other date functions (such as DATEDIF) when the parameter value is a string. +DATEVALUE uses the php date/time object implementation of strtotime() +(which can handle a wider range of formats than the normal strtotime() +function), and it is also called for any date parameter passed to other +date functions (such as DATEDIF) when the parameter value is a string. -__WARNING:-__ PhpSpreadsheet accepts a wider range of date formats than MS Excel, so it is entirely possible that Excel will return a #VALUE! error when passed a date string that it can’t interpret, while PhpSpreadsheet is able to translate that same string into a correct date value. +**WARNING:-** PhpSpreadsheet accepts a wider range of date formats than +MS Excel, so it is entirely possible that Excel will return a \#VALUE! +error when passed a date string that it can’t interpret, while +PhpSpreadsheet is able to translate that same string into a correct date +value. -Care should be taken in workbooks that use string formatted dates in calculations when writing to Xls or Xlsx. +Care should be taken in workbooks that use string formatted dates in +calculations when writing to Xls or Xlsx. #### DAY -The DAY function returns the day of a date. The day is given as an integer ranging from 1 to 31. +The DAY function returns the day of a date. The day is given as an +integer ranging from 1 to 31. ##### Syntax -``` -DAY(datetime) -``` + DAY(datetime) ##### Parameters **datetime** Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. ##### Return Value @@ -1117,7 +1328,7 @@ This is an integer ranging from 1 to 31. ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '31-Dec-2008') ->setCellValue('A3', '14-Feb-2008'); @@ -1132,7 +1343,7 @@ $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 14 ``` -```php +``` php $retVal = call_user_func_array( array('\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DAYOFMONTH'), array('25-Dec-2008') @@ -1142,31 +1353,36 @@ $retVal = call_user_func_array( ##### Notes -Note that the PhpSpreadsheet function is \PhpOffice\PhpSpreadsheet\Calculation\Functions::DAYOFMONTH() when the method is called statically. +Note that the PhpSpreadsheet function is +\PhpOffice\PhpSpreadsheet\Calculation\Functions::DAYOFMONTH() when the +method is called statically. #### DAYS360 -The DAYS360 function computes the difference between two dates based on a 360 day year (12 equal periods of 30 days each) used by some accounting systems. +The DAYS360 function computes the difference between two dates based on +a 360 day year (12 equal periods of 30 days each) used by some +accounting systems. ##### Syntax -``` -DAYS360(date1, date2 [, method]) -``` + DAYS360(date1, date2 [, method]) #### Parameters **date1** First Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **date2** Second Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **method** A boolean flag (TRUE or FALSE) -This is a flag that determines which method to use in the calculation, based on the values listed below: +This is a flag that determines which method to use in the calculation, +based on the values listed below: method | Description -------|------------ @@ -1177,13 +1393,15 @@ The method value defaults to FALSE. ##### Return Value -**integer** An integer value that reflects the difference between the two dates. +**integer** An integer value that reflects the difference between the +two dates. -This is the number of full days between the two dates, based on a 360 day year. +This is the number of full days between the two dates, based on a 360 +day year. ##### Examples -```php +``` php $worksheet->setCellValue('B1', 'Start Date') ->setCellValue('C1', 'End Date') ->setCellValue('A2', 'Year') @@ -1208,7 +1426,7 @@ $retVal = $worksheet->getCell('E4')->getCalculatedValue(); // $retVal = 1557 ``` -```php +``` php $date1 = 37655.0; // Excel timestamp for 25-Oct-2007 $date2 = 39233.0; // Excel timestamp for 8-Dec-2015 @@ -1227,37 +1445,48 @@ $retVal = call_user_func_array( ##### Notes -__WARNING:-__ This function does not currently work with the Xls Writer when a PHP Boolean is used for the third (optional) parameter (as shown in the example above), and the writer will generate and error. It will work if a numeric 0 or 1 is used for the method parameter; or if the Excel TRUE() and FALSE() functions are used instead. +**WARNING:-** This function does not currently work with the Xls Writer +when a PHP Boolean is used for the third (optional) parameter (as shown +in the example above), and the writer will generate and error. It will +work if a numeric 0 or 1 is used for the method parameter; or if the +Excel TRUE() and FALSE() functions are used instead. #### EDATE -The EDATE function returns an Excel timestamp or a PHP timestamp or date object representing the date that is the indicated number of months before or after a specified date (the start_date). Use EDATE to calculate maturity dates or due dates that fall on the same day of the month as the date of issue. +The EDATE function returns an Excel timestamp or a PHP timestamp or date +object representing the date that is the indicated number of months +before or after a specified date (the start\_date). Use EDATE to +calculate maturity dates or due dates that fall on the same day of the +month as the date of issue. ##### Syntax -``` -EDATE(baseDate, months) -``` + EDATE(baseDate, months) ##### Parameters **baseDate** Start Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **months** Number of months to add. -An integer value indicating the number of months before or after baseDate. A positive value for months yields a future date; a negative value yields a past date. +An integer value indicating the number of months before or after +baseDate. A positive value for months yields a future date; a negative +value yields a past date. ##### Return Value **mixed** A date/time stamp that corresponds to the basedate + months. -This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). +This could be a PHP timestamp value (integer), a PHP date/time object, +or an Excel timestamp value (real), depending on the value of +\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '1-Jan-2008') ->setCellValue('A3', '29-Feb-2008'); @@ -1276,7 +1505,7 @@ $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 39141.0 (28-Feb-2007) ``` -```php +``` php \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); @@ -1290,37 +1519,47 @@ $retVal = call_user_func_array( ###### Notes -__WARNING:-__ This function is currently not supported by the Xls Writer because it is not a standard function within Excel 5, but an add-in from the Analysis ToolPak. +**WARNING:-** This function is currently not supported by the Xls Writer +because it is not a standard function within Excel 5, but an add-in from +the Analysis ToolPak. #### EOMONTH -The EOMONTH function returns an Excel timestamp or a PHP timestamp or date object representing the date of the last day of the month that is the indicated number of months before or after a specified date (the start_date). Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. +The EOMONTH function returns an Excel timestamp or a PHP timestamp or +date object representing the date of the last day of the month that is +the indicated number of months before or after a specified date (the +start\_date). Use EOMONTH to calculate maturity dates or due dates that +fall on the last day of the month. ##### Syntax -``` -EOMONTH(baseDate, months) -``` + EOMONTH(baseDate, months) ##### Parameters **baseDate** Start Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **months** Number of months to add. -An integer value indicating the number of months before or after baseDate. A positive value for months yields a future date; a negative value yields a past date. +An integer value indicating the number of months before or after +baseDate. A positive value for months yields a future date; a negative +value yields a past date. ##### Return Value -**mixed** A date/time stamp that corresponds to the last day of basedate + months. +**mixed** A date/time stamp that corresponds to the last day of basedate ++ months. -This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). +This could be a PHP timestamp value (integer), a PHP date/time object, +or an Excel timestamp value (real), depending on the value of +\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '1-Jan-2000') ->setCellValue('A3', '14-Feb-2009'); @@ -1337,7 +1576,7 @@ $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 39507.0 (29-Feb-2008) ``` -```php +``` php \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); @@ -1351,23 +1590,25 @@ $retVal = call_user_func_array( ##### Notes -__WARNING:-__ This function is currently not supported by the Xls Writer because it is not a standard function within Excel 5, but an add-in from the Analysis ToolPak. +**WARNING:-** This function is currently not supported by the Xls Writer +because it is not a standard function within Excel 5, but an add-in from +the Analysis ToolPak. #### HOUR -The HOUR function returns the hour of a time value. The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.). +The HOUR function returns the hour of a time value. The hour is given as +an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.). ##### Syntax -``` -HOUR(datetime) -``` + HOUR(datetime) ##### Parameters **datetime** Time. -An Excel date/time value, PHP date timestamp, PHP date object, or a date/time represented as a string. +An Excel date/time value, PHP date timestamp, PHP date object, or a +date/time represented as a string. ##### Return Value @@ -1377,7 +1618,7 @@ This is an integer ranging from 0 to 23. ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Time String') ->setCellValue('A2', '31-Dec-2008 17:30') ->setCellValue('A3', '14-Feb-2008 4:20 AM') @@ -1397,7 +1638,7 @@ $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 16 ``` -```php +``` php $retVal = call_user_func_array( array('\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'HOUROFDAY'), array('09:30') @@ -1407,23 +1648,25 @@ $retVal = call_user_func_array( ##### Notes -Note that the PhpSpreadsheet function is \PhpOffice\PhpSpreadsheet\Calculation\Functions::HOUROFDAY() when the method is called statically. +Note that the PhpSpreadsheet function is +\PhpOffice\PhpSpreadsheet\Calculation\Functions::HOUROFDAY() when the +method is called statically. #### MINUTE -The MINUTE function returns the minutes of a time value. The minute is given as an integer, ranging from 0 to 59. +The MINUTE function returns the minutes of a time value. The minute is +given as an integer, ranging from 0 to 59. ##### Syntax -``` -MINUTE(datetime) -``` + MINUTE(datetime) ##### Parameters **datetime** Time. -An Excel date/time value, PHP date timestamp, PHP date object, or a date/time represented as a string. +An Excel date/time value, PHP date timestamp, PHP date object, or a +date/time represented as a string. ##### Return Value @@ -1433,7 +1676,7 @@ This is an integer ranging from 0 to 59. ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Time String') ->setCellValue('A2', '31-Dec-2008 17:30') ->setCellValue('A3', '14-Feb-2008 4:20 AM') @@ -1453,7 +1696,7 @@ $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 45 ``` -```php +``` php $retVal = call_user_func_array( array('\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'MINUTE'), array('09:30') @@ -1463,23 +1706,25 @@ $retVal = call_user_func_array( ##### Notes -Note that the PhpSpreadsheet function is \PhpOffice\PhpSpreadsheet\Calculation\Functions::MINUTE() when the method is called statically. +Note that the PhpSpreadsheet function is +\PhpOffice\PhpSpreadsheet\Calculation\Functions::MINUTE() when the +method is called statically. #### MONTH -The MONTH function returns the month of a date. The month is given as an integer ranging from 1 to 12. +The MONTH function returns the month of a date. The month is given as an +integer ranging from 1 to 12. ##### Syntax -``` -MONTH(datetime) -``` + MONTH(datetime) ##### Parameters **datetime** Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. ##### Return Value @@ -1489,7 +1734,7 @@ This is an integer ranging from 1 to 12. ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Date String'); $worksheet->setCellValue('A2', '31-Dec-2008'); $worksheet->setCellValue('A3', '14-Feb-2008'); @@ -1504,7 +1749,7 @@ $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 2 ``` -```php +``` php $retVal = call_user_func_array( array('\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'MONTHOFYEAR'), array('14-July-2008') @@ -1514,33 +1759,42 @@ $retVal = call_user_func_array( #### Notes -Note that the PhpSpreadsheet function is \PhpOffice\PhpSpreadsheet\Calculation\Functions::MONTHOFYEAR() when the method is called statically. +Note that the PhpSpreadsheet function is +\PhpOffice\PhpSpreadsheet\Calculation\Functions::MONTHOFYEAR() when the +method is called statically. #### NETWORKDAYS -The NETWORKDAYS function returns the number of whole working days between a *start date* and an *end date*. Working days exclude weekends and any dates identified in *holidays*. Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days worked during a specific term. +The NETWORKDAYS function returns the number of whole working days +between a *start date* and an *end date*. Working days exclude weekends +and any dates identified in *holidays*. Use NETWORKDAYS to calculate +employee benefits that accrue based on the number of days worked during +a specific term. ##### Syntax -``` -NETWORKDAYS(startDate, endDate [, holidays]) -``` + NETWORKDAYS(startDate, endDate [, holidays]) ##### Parameters **startDate** Start Date of the period. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **endDate** End Date of the period. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **holidays** Optional array of Holiday dates. -An optional range of one or more dates to exclude from the working calendar, such as state and federal holidays and floating holidays. +An optional range of one or more dates to exclude from the working +calendar, such as state and federal holidays and floating holidays. -The list can be either a range of cells that contains the dates or an array constant of Excel date values, PHP date timestamps, PHP date objects, or dates represented as strings. +The list can be either a range of cells that contains the dates or an +array constant of Excel date values, PHP date timestamps, PHP date +objects, or dates represented as strings. ##### Return Value @@ -1550,10 +1804,10 @@ The number of working days between startDate and endDate. ##### Examples -```php +``` php ``` -```php +``` php ``` ##### Notes @@ -1566,9 +1820,7 @@ The NOW function returns the current date and time. ##### Syntax -``` -NOW() -``` + NOW() ##### Parameters @@ -1576,47 +1828,53 @@ There are now parameters for the NOW() function. ##### Return Value -**mixed** A date/time stamp that corresponds to the current date and time. +**mixed** A date/time stamp that corresponds to the current date and +time. -This could be a PHP timestamp value (integer), a PHP date/time object, or an Excel timestamp value (real), depending on the value of \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). +This could be a PHP timestamp value (integer), a PHP date/time object, +or an Excel timestamp value (real), depending on the value of +\PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(). ##### Examples -```php +``` php ``` -```php +``` php ``` ##### Notes -Note that the PhpSpreadsheet function is \PhpOffice\PhpSpreadsheet\Calculation\Functions::DATETIMENOW() when the method is called statically. +Note that the PhpSpreadsheet function is +\PhpOffice\PhpSpreadsheet\Calculation\Functions::DATETIMENOW() when the +method is called statically. #### SECOND -The SECOND function returns the seconds of a time value. The second is given as an integer, ranging from 0 to 59. +The SECOND function returns the seconds of a time value. The second is +given as an integer, ranging from 0 to 59. ##### Syntax -``` -SECOND(datetime) -``` + SECOND(datetime) ##### Parameters **datetime** Time. -An Excel date/time value, PHP date timestamp, PHP date object, or a date/time represented as a string. +An Excel date/time value, PHP date timestamp, PHP date object, or a +date/time represented as a string. ##### Return Value -**integer** An integer value that reflects the seconds within the minute. +**integer** An integer value that reflects the seconds within the +minute. This is an integer ranging from 0 to 59. ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Time String') ->setCellValue('A2', '31-Dec-2008 17:30:20') ->setCellValue('A3', '14-Feb-2008 4:20 AM') @@ -1636,7 +1894,7 @@ $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 59 ``` -```php +``` php $retVal = call_user_func_array( array('\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'SECOND'), array('09:30:17') @@ -1646,7 +1904,9 @@ $retVal = call_user_func_array( ##### Notes -Note that the PhpSpreadsheet function is \PhpOffice\PhpSpreadsheet\Calculation\Functions::SECOND() when the method is called statically. +Note that the PhpSpreadsheet function is +\PhpOffice\PhpSpreadsheet\Calculation\Functions::SECOND() when the +method is called statically. #### TIME @@ -1662,23 +1922,25 @@ Not yet documented. #### WEEKDAY -The WEEKDAY function returns the day of the week for a given date. The day is given as an integer ranging from 1 to 7, although this can be modified to return a value between 0 and 6. +The WEEKDAY function returns the day of the week for a given date. The +day is given as an integer ranging from 1 to 7, although this can be +modified to return a value between 0 and 6. ##### Syntax -``` -WEEKDAY(datetime [, method]) -``` + WEEKDAY(datetime [, method]) ##### Parameters **datetime** Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. **method** An integer flag (values 0, 1 or 2) -This is a flag that determines which method to use in the calculation, based on the values listed below: +This is a flag that determines which method to use in the calculation, +based on the values listed below: method | Description :-----:|------------------------------------------ @@ -1692,11 +1954,12 @@ The method value defaults to 1. **integer** An integer value that reflects the day of the week. -This is an integer ranging from 1 to 7, or 0 to 6, depending on the value of method. +This is an integer ranging from 1 to 7, or 0 to 6, depending on the +value of method. ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '31-Dec-2008') ->setCellValue('A3', '14-Feb-2008'); @@ -1715,7 +1978,7 @@ $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 2 ``` -```php +``` php $retVal = call_user_func_array( array('\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'WEEKDAY'), array('14-July-2008') @@ -1725,7 +1988,9 @@ $retVal = call_user_func_array( ##### Notes -Note that the PhpSpreadsheet function is \PhpOffice\PhpSpreadsheet\Calculation\Functions::WEEKDAY() when the method is called statically. +Note that the PhpSpreadsheet function is +\PhpOffice\PhpSpreadsheet\Calculation\Functions::WEEKDAY() when the +method is called statically. #### WEEKNUM @@ -1741,15 +2006,14 @@ The YEAR function returns the year of a date. ##### Syntax -``` -YEAR(datetime) -``` + YEAR(datetime) ##### Parameters **datetime** Date. -An Excel date value, PHP date timestamp, PHP date object, or a date represented as a string. +An Excel date value, PHP date timestamp, PHP date object, or a date +represented as a string. ##### Return Value @@ -1759,7 +2023,7 @@ This is an integer year value. ##### Examples -```php +``` php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '17-Jul-1982') ->setCellValue('A3', '16-Apr-2009'); @@ -1774,7 +2038,7 @@ $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 2009 ``` -```php +``` php $retVal = call_user_func_array( array('\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'YEAR'), array('14-July-2001') @@ -1789,4 +2053,3 @@ There are no additional notes on this function ### YEARFRAC Not yet documented. - diff --git a/docs/topics/file-formats.md b/docs/topics/file-formats.md index 7b7b55f4..8a8ced3c 100644 --- a/docs/topics/file-formats.md +++ b/docs/topics/file-formats.md @@ -1,49 +1,126 @@ # File Formats -PhpSpreadsheet can read a number of different spreadsheet and file formats, although not all features are supported by all of the readers. Check the [features cross reference](../references/features-cross-reference.md) for a list that identifies which features are supported by which readers. +PhpSpreadsheet can read a number of different spreadsheet and file +formats, although not all features are supported by all of the readers. +Check the [features cross +reference](../references/features-cross-reference.md) for a list that +identifies which features are supported by which readers. Currently, PhpSpreadsheet supports the following File Types for Reading: ### Xls -The Microsoft Excel™ Binary file format (BIFF5 and BIFF8) is a binary file format that was used by Microsoft Excel™ between versions 95 and 2003. The format is supported (to various extents) by most spreadsheet programs. BIFF files normally have an extension of .xls. Documentation describing the format can be found online at [http://msdn.microsoft.com/en-us/library/cc313154(v=office.12).aspx](http://msdn.microsoft.com/en-us/library/cc313154(v=office.12).aspx) or from [as a downloadable PDF](http://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/[MS-XLS].pdf). +The Microsoft Excel™ Binary file format (BIFF5 and BIFF8) is a binary +file format that was used by Microsoft Excel™ between versions 95 and +2003. The format is supported (to various extents) by most spreadsheet +programs. BIFF files normally have an extension of .xls. Documentation +describing the format can be found online at + or +from [as a downloadable +PDF](http://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/%5BMS-XLS%5D.pdf). ### Excel2003XML -Microsoft Excel™ 2003 included options for a file format called SpreadsheetML. This file is a zipped XML document. It is not very common, but its core features are supported. Documentation for the format can be found at [http://msdn.microsoft.com/en-us/library/aa140066%28office.10%29.aspx](http://msdn.microsoft.com/en-us/library/aa140066%28office.10%29.aspx) though it’s sadly rather sparse in its detail. +Microsoft Excel™ 2003 included options for a file format called +SpreadsheetML. This file is a zipped XML document. It is not very +common, but its core features are supported. Documentation for the +format can be found at + +though it’s sadly rather sparse in its detail. ### Xlsx -Microsoft Excel™ 2007 shipped with a new file format, namely Microsoft Office Open XML SpreadsheetML, and Excel 2010 extended this still further with its new features such as sparklines. These files typically have an extension of .xlsx. This format is based around a zipped collection of eXtensible Markup Language (XML) files. Microsoft Office Open XML SpreadsheetML is mostly standardized in ECMA 376 ([http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm](http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm)) and ISO 29500. +Microsoft Excel™ 2007 shipped with a new file format, namely Microsoft +Office Open XML SpreadsheetML, and Excel 2010 extended this still +further with its new features such as sparklines. These files typically +have an extension of .xlsx. This format is based around a zipped +collection of eXtensible Markup Language (XML) files. Microsoft Office +Open XML SpreadsheetML is mostly standardized in ECMA 376 +() +and ISO 29500. ### Ods -aka Open Document Format (ODF) or OASIS, this is the OpenOffice.org XML File Format for spreadsheets. It comprises a zip archive including several components all of which are text files, most of these with markup in the eXtensible Markup Language (XML). It is the standard file format for OpenOffice.org Calc and StarCalc, and files typically have an extension of .ods. The published specification for the file format is available from the OASIS Open Office XML Format Technical Committee web page ([http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=office#technical](http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=office#technical)). Other information is available from the OpenOffice.org XML File Format web page ([http://xml.openoffice.org/general.html](http://xml.openoffice.org/general.html)), part of the OpenOffice.org project. +aka Open Document Format (ODF) or OASIS, this is the OpenOffice.org XML +File Format for spreadsheets. It comprises a zip archive including +several components all of which are text files, most of these with +markup in the eXtensible Markup Language (XML). It is the standard file +format for OpenOffice.org Calc and StarCalc, and files typically have an +extension of .ods. The published specification for the file format is +available from the OASIS Open Office XML Format Technical Committee web +page +(). +Other information is available from the OpenOffice.org XML File Format +web page (), part of the +OpenOffice.org project. ### SYLK -This is the Microsoft Multiplan Symbolic Link Interchange (SYLK) file format. Multiplan was a predecessor to Microsoft Excel™. Files normally have an extension of .slk. While not common, there are still a few applications that generate SYLK files as a cross-platform option, because (despite being limited to a single worksheet) it is a simple format to implement, and supports some basic data and cell formatting options (unlike CSV files). +This is the Microsoft Multiplan Symbolic Link Interchange (SYLK) file +format. Multiplan was a predecessor to Microsoft Excel™. Files normally +have an extension of .slk. While not common, there are still a few +applications that generate SYLK files as a cross-platform option, +because (despite being limited to a single worksheet) it is a simple +format to implement, and supports some basic data and cell formatting +options (unlike CSV files). ### Gnumeric -The Gnumeric file format is used by the Gnome Gnumeric spreadsheet application, and typically files have an extension of .gnumeric. The file contents are stored using eXtensible Markup Language (XML) markup, and the file is then compressed using the GNU project's gzip compression library. [http://projects.gnome.org/gnumeric/doc/file-format-gnumeric.shtml](http://projects.gnome.org/gnumeric/doc/file-format-gnumeric.shtml) +The Gnumeric file format is used by the Gnome Gnumeric spreadsheet +application, and typically files have an extension of .gnumeric. The +file contents are stored using eXtensible Markup Language (XML) markup, +and the file is then compressed using the GNU project's gzip compression +library. + ### CSV -Comma Separated Value (CSV) file format is a common structuring strategy for text format files. In CSV flies, each line in the file represents a row of data and (within each line of the file) the different data fields (or columns) are separated from one another using a comma (","). If a data field contains a comma, then it should be enclosed (typically in quotation marks ("). Sometimes tabs "\t", or the pipe symbol ("|"), or a semi-colon (";") are used as separators instead of a comma, although other symbols can be used. Because CSV is a text-only format, it doesn't support any data formatting options. +Comma Separated Value (CSV) file format is a common structuring strategy +for text format files. In CSV flies, each line in the file represents a +row of data and (within each line of the file) the different data fields +(or columns) are separated from one another using a comma (","). If a +data field contains a comma, then it should be enclosed (typically in +quotation marks ("). Sometimes tabs "\t", or the pipe symbol ("|"), or a +semi-colon (";") are used as separators instead of a comma, although +other symbols can be used. Because CSV is a text-only format, it doesn't +support any data formatting options. -"CSV" is not a single, well-defined format (although see RFC 4180 for one definition that is commonly used). Rather, in practice the term "CSV" refers to any file that: +"CSV" is not a single, well-defined format (although see RFC 4180 for +one definition that is commonly used). Rather, in practice the term +"CSV" refers to any file that: -- is plain text using a character set such as ASCII, Unicode, EBCDIC, or Shift JIS, -- consists of records (typically one record per line), -- with the records divided into fields separated by delimiters (typically a single reserved character such as comma, semicolon, or tab, -- where every record has the same sequence of fields. +- is plain text using a character set such as ASCII, Unicode, EBCDIC, + or Shift JIS, +- consists of records (typically one record per line), +- with the records divided into fields separated by delimiters + (typically a single reserved character such as comma, semicolon, or + tab, +- where every record has the same sequence of fields. -Within these general constraints, many variations are in use. Therefore "CSV" files are not entirely portable. Nevertheless, the variations are fairly small, and many implementations allow users to glance at the file (which is feasible because it is plain text), and then specify the delimiter character(s), quoting rules, etc. +Within these general constraints, many variations are in use. Therefore +"CSV" files are not entirely portable. Nevertheless, the variations are +fairly small, and many implementations allow users to glance at the file +(which is feasible because it is plain text), and then specify the +delimiter character(s), quoting rules, etc. -**Warning:** Microsoft Excel™ will open .csv files, but depending on the system's regional settings, it may expect a semicolon as a separator instead of a comma, since in some languages the comma is used as the decimal separator. Also, many regional versions of Excel will not be able to deal with Unicode characters in a CSV file. +**Warning:** Microsoft Excel™ will open .csv files, but depending on the +system's regional settings, it may expect a semicolon as a separator +instead of a comma, since in some languages the comma is used as the +decimal separator. Also, many regional versions of Excel will not be +able to deal with Unicode characters in a CSV file. ### HTML -HyperText Markup Language (HTML) is the main markup language for creating web pages and other information that can be displayed in a web browser. Files typically have an extension of .html or .htm. HTML markup provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. Since 1996, the HTML specifications have been maintained, with input from commercial software vendors, by the World Wide Web Consortium (W3C). However, in 2000, HTML also became an international standard (ISO/IEC 15445:2000). HTML 4.01 was published in late 1999, with further errata published through 2001. In 2004 development began on HTML5 in the Web Hypertext Application Technology Working Group (WHATWG), which became a joint deliverable with the W3C in 2008. - +HyperText Markup Language (HTML) is the main markup language for +creating web pages and other information that can be displayed in a web +browser. Files typically have an extension of .html or .htm. HTML markup +provides a means to create structured documents by denoting structural +semantics for text such as headings, paragraphs, lists, links, quotes +and other items. Since 1996, the HTML specifications have been +maintained, with input from commercial software vendors, by the World +Wide Web Consortium (W3C). However, in 2000, HTML also became an +international standard (ISO/IEC 15445:2000). HTML 4.01 was published in +late 1999, with further errata published through 2001. In 2004 +development began on HTML5 in the Web Hypertext Application Technology +Working Group (WHATWG), which became a joint deliverable with the W3C in +2008. diff --git a/docs/topics/migration-from-PHPExcel.md b/docs/topics/migration-from-PHPExcel.md index e170607b..a7cd1134 100644 --- a/docs/topics/migration-from-PHPExcel.md +++ b/docs/topics/migration-from-PHPExcel.md @@ -1,17 +1,18 @@ # Migration from PHPExcel -PhpSpreadsheet introduced many breaking changes by introducing namespaces and -renaming some classes. To help you migrate existing project, a tool was written -to replace all references to PHPExcel classes to their new names. +PhpSpreadsheet introduced many breaking changes by introducing +namespaces and renaming some classes. To help you migrate existing +project, a tool was written to replace all references to PHPExcel +classes to their new names. -The tool is included in PhpSpreadsheet. It scans recursively all files and -directories, starting from the current directory. Assuming it was installed with -composer, it can be run like so: +The tool is included in PhpSpreadsheet. It scans recursively all files +and directories, starting from the current directory. Assuming it was +installed with composer, it can be run like so: -```sh +``` sh cd /project/to/migrate/src /project/to/migrate/vendor/phpoffice/phpspreadsheet/bin/migrate-from-phpexcel ``` -**Important** The tool will irreversibly modify your sources, be sure to backup -everything, and double check the result before committing. \ No newline at end of file +**Important** The tool will irreversibly modify your sources, be sure to +backup everything, and double check the result before committing. diff --git a/docs/topics/reading-files.md b/docs/topics/reading-files.md index 77f5c2c8..5e4aa781 100644 --- a/docs/topics/reading-files.md +++ b/docs/topics/reading-files.md @@ -1,41 +1,64 @@ # Reading Files - ## Security -XML-based formats such as OfficeOpen XML, Excel2003 XML, OASIS and Gnumeric are susceptible to XML External Entity Processing (XXE) injection attacks (for an explanation of XXE injection see http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html) when reading spreadsheet files. This can lead to: +XML-based formats such as OfficeOpen XML, Excel2003 XML, OASIS and +Gnumeric are susceptible to XML External Entity Processing (XXE) +injection attacks (for an explanation of XXE injection see +http://websec.io/2012/08/27/Preventing-XEE-in-PHP.html) when reading +spreadsheet files. This can lead to: - - Disclosure whether a file is existent - - Server Side Request Forgery - - Command Execution (depending on the installed PHP wrappers) +- Disclosure whether a file is existent +- Server Side Request Forgery +- Command Execution (depending on the installed PHP wrappers) - -To prevent this, PhpSpreadsheet sets `libxml_disable_entity_loader` to `true` for the XML-based Readers by default. +To prevent this, PhpSpreadsheet sets `libxml_disable_entity_loader` to +`true` for the XML-based Readers by default. ## Loading a Spreadsheet File -The simplest way to load a workbook file is to let PhpSpreadsheet's IO Factory identify the file type and load it, calling the static load() method of the \PhpOffice\PhpSpreadsheet\IOFactory class. +The simplest way to load a workbook file is to let PhpSpreadsheet's IO +Factory identify the file type and load it, calling the static load() +method of the \PhpOffice\PhpSpreadsheet\IOFactory class. -```php +``` php $inputFileName = './sampleData/example1.xls'; /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName); ``` - > See Examples/Reader/exampleReader01.php for a working example of this code. -The load() method will attempt to identify the file type, and instantiate a loader for that file type; using it to load the file and store the data and any formatting in a `Spreadsheet` object. +> See Examples/Reader/exampleReader01.php for a working example of this +> code. -The method makes an initial guess at the loader to instantiate based on the file extension; but will test the file before actually executing the load: so if (for example) the file is actually a CSV file or contains HTML markup, but that has been given a .xls extension (quite a common practise), it will reject the Xls loader that it would normally use for a .xls file; and test the file using the other loaders until it finds the appropriate loader, and then use that to read the file. +The load() method will attempt to identify the file type, and +instantiate a loader for that file type; using it to load the file and +store the data and any formatting in a `Spreadsheet` object. -While easy to implement in your code, and you don't need to worry about the file type; this isn't the most efficient method to load a file; and it lacks the flexibility to configure the loader in any way before actually reading the file into a `Spreadsheet` object. +The method makes an initial guess at the loader to instantiate based on +the file extension; but will test the file before actually executing the +load: so if (for example) the file is actually a CSV file or contains +HTML markup, but that has been given a .xls extension (quite a common +practise), it will reject the Xls loader that it would normally use for +a .xls file; and test the file using the other loaders until it finds +the appropriate loader, and then use that to read the file. +While easy to implement in your code, and you don't need to worry about +the file type; this isn't the most efficient method to load a file; and +it lacks the flexibility to configure the loader in any way before +actually reading the file into a `Spreadsheet` object. ## Creating a Reader and Loading a Spreadsheet File -If you know the file type of the spreadsheet file that you need to load, you can instantiate a new reader object for that file type, then use the reader's load() method to read the file to a `Spreadsheet` object. It is possible to instantiate the reader objects for each of the different supported filetype by name. However, you may get unpredictable results if the file isn't of the right type (e.g. it is a CSV with an extension of .xls), although this type of exception should normally be trapped. +If you know the file type of the spreadsheet file that you need to load, +you can instantiate a new reader object for that file type, then use the +reader's load() method to read the file to a `Spreadsheet` object. It is +possible to instantiate the reader objects for each of the different +supported filetype by name. However, you may get unpredictable results +if the file isn't of the right type (e.g. it is a CSV with an extension +of .xls), although this type of exception should normally be trapped. -```php +``` php $inputFileName = './sampleData/example1.xls'; /** Create a new Xls Reader **/ @@ -49,11 +72,15 @@ $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader02.php for a working example of this code. -Alternatively, you can use the IO Factory's createReader() method to instantiate the reader object for you, simply telling it the file type of the reader that you want instantiating. +> See Examples/Reader/exampleReader02.php for a working example of this +> code. -```php +Alternatively, you can use the IO Factory's createReader() method to +instantiate the reader object for you, simply telling it the file type +of the reader that you want instantiating. + +``` php $inputFileType = 'Xls'; // $inputFileType = 'Xlsx'; // $inputFileType = 'Excel2003XML'; @@ -68,11 +95,15 @@ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader03.php for a working example of this code. -If you're uncertain of the filetype, you can use the IO Factory's identify() method to identify the reader that you need, before using the createReader() method to instantiate the reader object. +> See Examples/Reader/exampleReader03.php for a working example of this +> code. -```php +If you're uncertain of the filetype, you can use the IO Factory's +identify() method to identify the reader that you need, before using the +createReader() method to instantiate the reader object. + +``` php $inputFileName = './sampleData/example1.xls'; /** Identify the type of $inputFileName **/ @@ -82,17 +113,24 @@ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader04.php for a working example of this code. + +> See Examples/Reader/exampleReader04.php for a working example of this +> code. ## Spreadsheet Reader Options -Once you have created a reader object for the workbook that you want to load, you have the opportunity to set additional options before executing the load() method. +Once you have created a reader object for the workbook that you want to +load, you have the opportunity to set additional options before +executing the load() method. ### Reading Only Data from a Spreadsheet File -If you're only interested in the cell values in a workbook, but don't need any of the cell formatting information, then you can set the reader to read only the data values and any formulae from each cell using the setReadDataOnly() method. +If you're only interested in the cell values in a workbook, but don't +need any of the cell formatting information, then you can set the reader +to read only the data values and any formulae from each cell using the +setReadDataOnly() method. -```php +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; @@ -103,11 +141,21 @@ $reader->setReadDataOnly(true); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader05.php for a working example of this code. -It is important to note that Workbooks (and PhpSpreadsheet) store dates and times as simple numeric values: they can only be distinguished from other numeric values by the format mask that is applied to that cell. When setting read data only to true, PhpSpreadsheet doesn't read the cell format masks, so it is not possible to differentiate between dates/times and numbers. +> See Examples/Reader/exampleReader05.php for a working example of this +> code. -The Gnumeric loader has been written to read the format masks for date values even when read data only has been set to true, so it can differentiate between dates/times and numbers; but this change hasn't yet been implemented for the other readers. +It is important to note that Workbooks (and PhpSpreadsheet) store dates +and times as simple numeric values: they can only be distinguished from +other numeric values by the format mask that is applied to that cell. +When setting read data only to true, PhpSpreadsheet doesn't read the +cell format masks, so it is not possible to differentiate between +dates/times and numbers. + +The Gnumeric loader has been written to read the format masks for date +values even when read data only has been set to true, so it can +differentiate between dates/times and numbers; but this change hasn't +yet been implemented for the other readers. Reading Only Data from a Spreadsheet File applies to Readers: @@ -119,11 +167,15 @@ CSV | NO | HTML | NO ### Reading Only Named WorkSheets from a File -If your workbook contains a number of worksheets, but you are only interested in reading some of those, then you can use the setLoadSheetsOnly() method to identify those sheets you are interested in reading. +If your workbook contains a number of worksheets, but you are only +interested in reading some of those, then you can use the +setLoadSheetsOnly() method to identify those sheets you are interested +in reading. -To read a single sheet, you can pass that sheet name as a parameter to the setLoadSheetsOnly() method. +To read a single sheet, you can pass that sheet name as a parameter to +the setLoadSheetsOnly() method. -```php +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetname = 'Data Sheet #2'; @@ -135,11 +187,14 @@ $reader->setLoadSheetsOnly($sheetname); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader07.php for a working example of this code. -If you want to read more than just a single sheet, you can pass a list of sheet names as an array parameter to the setLoadSheetsOnly() method. +> See Examples/Reader/exampleReader07.php for a working example of this +> code. -```php +If you want to read more than just a single sheet, you can pass a list +of sheet names as an array parameter to the setLoadSheetsOnly() method. + +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetnames = array('Data Sheet #1','Data Sheet #3'); @@ -151,11 +206,14 @@ $reader->setLoadSheetsOnly($sheetnames); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader08.php for a working example of this code. -To reset this option to the default, you can call the setLoadAllSheets() method. +> See Examples/Reader/exampleReader08.php for a working example of this +> code. -```php +To reset this option to the default, you can call the setLoadAllSheets() +method. + +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; @@ -166,7 +224,9 @@ $reader->setLoadAllSheets(); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader06.php for a working example of this code. + +> See Examples/Reader/exampleReader06.php for a working example of this +> code. Reading Only Named WorkSheets from a File applies to Readers: @@ -178,9 +238,16 @@ CSV | NO | HTML | NO ### Reading Only Specific Columns and Rows from a File (Read Filters) -If you are only interested in reading part of a worksheet, then you can write a filter class that identifies whether or not individual cells should be read by the loader. A read filter must implement the \PhpOffice\PhpSpreadsheet\Reader\IReadFilter interface, and contain a readCell() method that accepts arguments of $column, $row and $worksheetName, and return a boolean true or false that indicates whether a workbook cell identified by those arguments should be read or not. +If you are only interested in reading part of a worksheet, then you can +write a filter class that identifies whether or not individual cells +should be read by the loader. A read filter must implement the +\PhpOffice\PhpSpreadsheet\Reader\IReadFilter interface, and contain a +readCell() method that accepts arguments of \$column, \$row and +\$worksheetName, and return a boolean true or false that indicates +whether a workbook cell identified by those arguments should be read or +not. -```php +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetname = 'Data Sheet #3'; @@ -210,11 +277,16 @@ $reader->setReadFilter($filterSubset); /** Load only the rows and columns that match our filter to Spreadsheet **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader09.php for a working example of this code. -This example is not particularly useful, because it can only be used in a very specific circumstance (when you only want cells in the range A1:E7 from your worksheet. A generic Read Filter would probably be more useful: +> See Examples/Reader/exampleReader09.php for a working example of this +> code. -```php +This example is not particularly useful, because it can only be used in +a very specific circumstance (when you only want cells in the range +A1:E7 from your worksheet. A generic Read Filter would probably be more +useful: + +``` php /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { @@ -243,11 +315,16 @@ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter /** Create an Instance of our Read Filter, passing in the cell range **/ $filterSubset = new MyReadFilter(9,15,range('G','K')); ``` - > See Examples/Reader/exampleReader10.php for a working example of this code. -This can be particularly useful for conserving memory, by allowing you to read and process a large workbook in “chunks”: an example of this usage might be when transferring data from an Excel worksheet to a database. +> See Examples/Reader/exampleReader10.php for a working example of this +> code. -```php +This can be particularly useful for conserving memory, by allowing you +to read and process a large workbook in “chunks”: an example of this +usage might be when transferring data from an Excel worksheet to a +database. + +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example2.xls'; @@ -295,21 +372,31 @@ for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) { // Do some processing here } ``` - > See Examples/Reader/exampleReader12.php for a working example of this code. + +> See Examples/Reader/exampleReader12.php for a working example of this +> code. Using Read Filters applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| -Xlsx | YES | Xls | YES | Excel2003XML | YES | -Ods | YES | SYLK | NO | Gnumeric | YES | -CSV | YES | HTML | NO +Xlsx | YES | Xls | YES | Excel2003XML | YES | +Ods | YES | SYLK | NO | Gnumeric | YES | +CSV | YES | HTML | NO | | | ### Combining Multiple Files into a Single Spreadsheet Object -While you can limit the number of worksheets that are read from a workbook file using the setLoadSheetsOnly() method, certain readers also allow you to combine several individual "sheets" from different files into a single `Spreadsheet` object, where each individual file is a single worksheet within that workbook. For each file that you read, you need to indicate which worksheet index it should be loaded into using the setSheetIndex() method of the $reader, then use the loadIntoExisting() method rather than the load() method to actually read the file into that worksheet. +While you can limit the number of worksheets that are read from a +workbook file using the setLoadSheetsOnly() method, certain readers also +allow you to combine several individual "sheets" from different files +into a single `Spreadsheet` object, where each individual file is a +single worksheet within that workbook. For each file that you read, you +need to indicate which worksheet index it should be loaded into using +the setSheetIndex() method of the \$reader, then use the +loadIntoExisting() method rather than the load() method to actually read +the file into that worksheet. -```php +``` php $inputFileType = 'CSV'; $inputFileNames = array('./sampleData/example1.csv', './sampleData/example2.csv' @@ -340,23 +427,36 @@ foreach($inputFileNames as $sheet => $inputFileName) { ->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME)); } ``` - > See Examples/Reader/exampleReader13.php for a working example of this code. -Note that using the same sheet index for multiple sheets won't append files into the same sheet, but overwrite the results of the previous load. You cannot load multiple CSV files into the same worksheet. +> See Examples/Reader/exampleReader13.php for a working example of this +> code. + +Note that using the same sheet index for multiple sheets won't append +files into the same sheet, but overwrite the results of the previous +load. You cannot load multiple CSV files into the same worksheet. Combining Multiple Files into a Single Spreadsheet Object applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| -Xlsx | NO | Xls | NO | Excel2003XML | NO | -Ods | NO | SYLK | YES | Gnumeric | NO | +Xlsx | NO | Xls | NO | Excel2003XML | NO | +Ods | NO | SYLK | YES | Gnumeric | NO | CSV | YES | HTML | NO -### Combining Read Filters with the setSheetIndex() method to split a large CSV file across multiple Worksheets +### Combining Read Filters with the setSheetIndex() method to split a large CSV file across multiple Worksheets -An Xls BIFF .xls file is limited to 65536 rows in a worksheet, while the Xlsx Microsoft Office Open XML SpreadsheetML .xlsx file is limited to 1,048,576 rows in a worksheet; but a CSV file is not limited other than by available disk space. This means that we wouldn’t ordinarily be able to read all the rows from a very large CSV file that exceeded those limits, and save it as an Xls or Xlsx file. However, by using Read Filters to read the CSV file in “chunks” (using the chunkReadFilter Class that we defined in section REF _Ref275604563 \r \p 5.3 above), and the setSheetIndex() method of the $reader, we can split the CSV file across several individual worksheets. +An Xls BIFF .xls file is limited to 65536 rows in a worksheet, while the +Xlsx Microsoft Office Open XML SpreadsheetML .xlsx file is limited to +1,048,576 rows in a worksheet; but a CSV file is not limited other than +by available disk space. This means that we wouldn’t ordinarily be able +to read all the rows from a very large CSV file that exceeded those +limits, and save it as an Xls or Xlsx file. However, by using Read +Filters to read the CSV file in “chunks” (using the chunkReadFilter +Class that we defined in section REF \_Ref275604563 \r \p 5.3 above), +and the setSheetIndex() method of the \$reader, we can split the CSV +file across several individual worksheets. -```php +``` php $inputFileType = 'CSV'; $inputFileName = './sampleData/example2.csv'; @@ -397,27 +497,38 @@ for ($startRow = 2; $startRow <= 1000000; $startRow += $chunkSize) { $spreadsheet->getActiveSheet()->setTitle('Country Data #'.(++$sheet)); } ``` - > See Examples/Reader/exampleReader14.php for a working example of this code. -This code will read 65,530 rows at a time from the CSV file that we’re loading, and store each "chunk" in a new worksheet. +> See Examples/Reader/exampleReader14.php for a working example of this +> code. -The setContiguous() method for the Reader is important here. It is applicable only when working with a Read Filter, and identifies whether or not the cells should be stored by their position within the CSV file, or their position relative to the filter. +This code will read 65,530 rows at a time from the CSV file that we’re +loading, and store each "chunk" in a new worksheet. -For example, if the filter returned true for cells in the range B2:C3, then with setContiguous set to false (the default) these would be loaded as B2:C3 in the `Spreadsheet` object; but with setContiguous set to true, they would be loaded as A1:B2. +The setContiguous() method for the Reader is important here. It is +applicable only when working with a Read Filter, and identifies whether +or not the cells should be stored by their position within the CSV file, +or their position relative to the filter. + +For example, if the filter returned true for cells in the range B2:C3, +then with setContiguous set to false (the default) these would be loaded +as B2:C3 in the `Spreadsheet` object; but with setContiguous set to +true, they would be loaded as A1:B2. Splitting a single loaded file across multiple worksheets applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| -Xlsx | NO | Xls | NO | Excel2003XML | NO | -Ods | NO | SYLK | NO | Gnumeric | NO | +Xlsx | NO | Xls | NO | Excel2003XML | NO | +Ods | NO | SYLK | NO | Gnumeric | NO | CSV | YES | HTML | NO ### Pipe or Tab Separated Value Files -The CSV loader defaults to loading a file where comma is used as the separator, but you can modify this to load tab- or pipe-separated value files using the setDelimiter() method. +The CSV loader defaults to loading a file where comma is used as the +separator, but you can modify this to load tab- or pipe-separated value +files using the setDelimiter() method. -```php +``` php $inputFileType = 'CSV'; $inputFileName = './sampleData/example1.tsv'; @@ -429,31 +540,54 @@ $reader->setDelimiter("\t"); /** Load the file to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader15.php for a working example of this code. -In addition to the delimiter, you can also use the following methods to set other attributes for the data load: +> See Examples/Reader/exampleReader15.php for a working example of this +> code. -setEnclosure() | default is " -setLineEnding() | default is PHP_EOL +In addition to the delimiter, you can also use the following methods to +set other attributes for the data load: + +setEnclosure() | default is " setLineEnding() | default is PHP\_EOL setInputEncoding() | default is UTF-8 Setting CSV delimiter applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| -Xlsx | NO | Xls | NO | Excel2003XML | NO | -Ods | NO | SYLK | NO | Gnumeric | NO | +Xlsx | NO | Xls | NO | Excel2003XML | NO | +Ods | NO | SYLK | NO | Gnumeric | NO | CSV | YES | HTML | NO ### A Brief Word about the Advanced Value Binder -When loading data from a file that contains no formatting information, such as a CSV file, then data is read either as strings or numbers (float or integer). This means that PhpSpreadsheet does not automatically recognise dates/times (such as "16-Apr-2009" or "13:30"), booleans ("TRUE" or "FALSE"), percentages ("75%"), hyperlinks ("http://www.phpexcel.net"), etc as anything other than simple strings. However, you can apply additional processing that is executed against these values during the load process within a Value Binder. +When loading data from a file that contains no formatting information, +such as a CSV file, then data is read either as strings or numbers +(float or integer). This means that PhpSpreadsheet does not +automatically recognise dates/times (such as "16-Apr-2009" or "13:30"), +booleans ("TRUE" or "FALSE"), percentages ("75%"), hyperlinks +("http://www.phpexcel.net"), etc as anything other than simple strings. +However, you can apply additional processing that is executed against +these values during the load process within a Value Binder. -A Value Binder is a class that implement the \PhpOffice\PhpSpreadsheet\Cell\IValueBinder interface. It must contain a bindValue() method that accepts a \PhpOffice\PhpSpreadsheet\Cell and a value as arguments, and return a boolean true or false that indicates whether the workbook cell has been populated with the value or not. The Advanced Value Binder implements such a class: amongst other tests, it identifies a string comprising "TRUE" or "FALSE" (based on locale settings) and sets it to a boolean; or a number in scientific format (e.g. "1.234e-5") and converts it to a float; or dates and times, converting them to their Excel timestamp value – before storing the value in the cell object. It also sets formatting for strings that are identified as dates, times or percentages. It could easily be extended to provide additional handling (including text or cell formatting) when it encountered a hyperlink, or HTML markup within a CSV file. +A Value Binder is a class that implement the +\PhpOffice\PhpSpreadsheet\Cell\IValueBinder interface. It must contain a +bindValue() method that accepts a \PhpOffice\PhpSpreadsheet\Cell and a +value as arguments, and return a boolean true or false that indicates +whether the workbook cell has been populated with the value or not. The +Advanced Value Binder implements such a class: amongst other tests, it +identifies a string comprising "TRUE" or "FALSE" (based on locale +settings) and sets it to a boolean; or a number in scientific format +(e.g. "1.234e-5") and converts it to a float; or dates and times, +converting them to their Excel timestamp value – before storing the +value in the cell object. It also sets formatting for strings that are +identified as dates, times or percentages. It could easily be extended +to provide additional handling (including text or cell formatting) when +it encountered a hyperlink, or HTML markup within a CSV file. -So using a Value Binder allows a great deal more flexibility in the loader logic when reading unformatted text files. +So using a Value Binder allows a great deal more flexibility in the +loader logic when reading unformatted text files. -```php +``` php /** Tell PhpSpreadsheet that we want to use the Advanced Value Binder **/ \PhpOffice\PhpSpreadsheet\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); @@ -464,27 +598,32 @@ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); $reader->setDelimiter("\t"); $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader15.php for a working example of this code. + +> See Examples/Reader/exampleReader15.php for a working example of this +> code. Loading using a Value Binder applies to: Reader | Y/N |Reader | Y/N |Reader | Y/N ----------|:---:|--------|:---:|--------------|:---: -Xlsx | NO | Xls | NO | Excel2003XML | NO -Ods | NO | SYLK | NO | Gnumeric | NO +Xlsx | NO | Xls | NO | Excel2003XML | NO +Ods | NO | SYLK | NO | Gnumeric | NO CSV | YES | HTML | YES - - ## Spreadsheet Reader Options -Once you have created a reader object for the workbook that you want to load, you have the opportunity to set additional options before executing the load() method. +Once you have created a reader object for the workbook that you want to +load, you have the opportunity to set additional options before +executing the load() method. ### Reading Only Data from a Spreadsheet File -If you're only interested in the cell values in a workbook, but don't need any of the cell formatting information, then you can set the reader to read only the data values and any formulae from each cell using the setReadDataOnly() method. +If you're only interested in the cell values in a workbook, but don't +need any of the cell formatting information, then you can set the reader +to read only the data values and any formulae from each cell using the +setReadDataOnly() method. -```php +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; @@ -495,27 +634,41 @@ $reader->setReadDataOnly(true); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader05.php for a working example of this code. -It is important to note that Workbooks (and PhpSpreadsheet) store dates and times as simple numeric values: they can only be distinguished from other numeric values by the format mask that is applied to that cell. When setting read data only to true, PhpSpreadsheet doesn't read the cell format masks, so it is not possible to differentiate between dates/times and numbers. +> See Examples/Reader/exampleReader05.php for a working example of this +> code. -The Gnumeric loader has been written to read the format masks for date values even when read data only has been set to true, so it can differentiate between dates/times and numbers; but this change hasn't yet been implemented for the other readers. +It is important to note that Workbooks (and PhpSpreadsheet) store dates +and times as simple numeric values: they can only be distinguished from +other numeric values by the format mask that is applied to that cell. +When setting read data only to true, PhpSpreadsheet doesn't read the +cell format masks, so it is not possible to differentiate between +dates/times and numbers. + +The Gnumeric loader has been written to read the format masks for date +values even when read data only has been set to true, so it can +differentiate between dates/times and numbers; but this change hasn't +yet been implemented for the other readers. Reading Only Data from a Spreadsheet File applies to Readers: Reader | Y/N |Reader | Y/N |Reader | Y/N | ----------|:---:|--------|:---:|--------------|:---:| -Xlsx | YES | Xls | YES | Excel2003XML | YES | -Ods | YES | SYLK | NO | Gnumeric | YES | +Xlsx | YES | Xls | YES | Excel2003XML | YES | +Ods | YES | SYLK | NO | Gnumeric | YES | CSV | NO | HTML | NO ### Reading Only Named WorkSheets from a File -If your workbook contains a number of worksheets, but you are only interested in reading some of those, then you can use the setLoadSheetsOnly() method to identify those sheets you are interested in reading. +If your workbook contains a number of worksheets, but you are only +interested in reading some of those, then you can use the +setLoadSheetsOnly() method to identify those sheets you are interested +in reading. -To read a single sheet, you can pass that sheet name as a parameter to the setLoadSheetsOnly() method. +To read a single sheet, you can pass that sheet name as a parameter to +the setLoadSheetsOnly() method. -```php +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetname = 'Data Sheet #2'; @@ -527,11 +680,14 @@ $reader->setLoadSheetsOnly($sheetname); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader07.php for a working example of this code. -If you want to read more than just a single sheet, you can pass a list of sheet names as an array parameter to the setLoadSheetsOnly() method. +> See Examples/Reader/exampleReader07.php for a working example of this +> code. -```php +If you want to read more than just a single sheet, you can pass a list +of sheet names as an array parameter to the setLoadSheetsOnly() method. + +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetnames = array('Data Sheet #1','Data Sheet #3'); @@ -543,11 +699,14 @@ $reader->setLoadSheetsOnly($sheetnames); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader08.php for a working example of this code. -To reset this option to the default, you can call the setLoadAllSheets() method. +> See Examples/Reader/exampleReader08.php for a working example of this +> code. -```php +To reset this option to the default, you can call the setLoadAllSheets() +method. + +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; @@ -558,7 +717,9 @@ $reader->setLoadAllSheets(); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader06.php for a working example of this code. + +> See Examples/Reader/exampleReader06.php for a working example of this +> code. Reading Only Named WorkSheets from a File applies to Readers: @@ -570,9 +731,16 @@ CSV | NO | HTML | NO ### Reading Only Specific Columns and Rows from a File (Read Filters) -If you are only interested in reading part of a worksheet, then you can write a filter class that identifies whether or not individual cells should be read by the loader. A read filter must implement the \PhpOffice\PhpSpreadsheet\Reader\IReadFilter interface, and contain a readCell() method that accepts arguments of $column, $row and $worksheetName, and return a boolean true or false that indicates whether a workbook cell identified by those arguments should be read or not. +If you are only interested in reading part of a worksheet, then you can +write a filter class that identifies whether or not individual cells +should be read by the loader. A read filter must implement the +\PhpOffice\PhpSpreadsheet\Reader\IReadFilter interface, and contain a +readCell() method that accepts arguments of \$column, \$row and +\$worksheetName, and return a boolean true or false that indicates +whether a workbook cell identified by those arguments should be read or +not. -```php +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example1.xls'; $sheetname = 'Data Sheet #3'; @@ -602,11 +770,16 @@ $reader->setReadFilter($filterSubset); /** Load only the rows and columns that match our filter to Spreadsheet **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader09.php for a working example of this code. -This example is not particularly useful, because it can only be used in a very specific circumstance (when you only want cells in the range A1:E7 from your worksheet. A generic Read Filter would probably be more useful: +> See Examples/Reader/exampleReader09.php for a working example of this +> code. -```php +This example is not particularly useful, because it can only be used in +a very specific circumstance (when you only want cells in the range +A1:E7 from your worksheet. A generic Read Filter would probably be more +useful: + +``` php /** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter { @@ -635,11 +808,16 @@ class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter /** Create an Instance of our Read Filter, passing in the cell range **/ $filterSubset = new MyReadFilter(9,15,range('G','K')); ``` - > See Examples/Reader/exampleReader10.php for a working example of this code. -This can be particularly useful for conserving memory, by allowing you to read and process a large workbook in “chunks”: an example of this usage might be when transferring data from an Excel worksheet to a database. +> See Examples/Reader/exampleReader10.php for a working example of this +> code. -```php +This can be particularly useful for conserving memory, by allowing you +to read and process a large workbook in “chunks”: an example of this +usage might be when transferring data from an Excel worksheet to a +database. + +``` php $inputFileType = 'Xls'; $inputFileName = './sampleData/example2.xls'; @@ -687,7 +865,9 @@ for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) { // Do some processing here } ``` - > See Examples/Reader/exampleReader12.php for a working example of this code. + +> See Examples/Reader/exampleReader12.php for a working example of this +> code. Using Read Filters applies to: @@ -699,9 +879,17 @@ CSV | YES | HTML | NO ### Combining Multiple Files into a Single Spreadsheet Object -While you can limit the number of worksheets that are read from a workbook file using the setLoadSheetsOnly() method, certain readers also allow you to combine several individual "sheets" from different files into a single `Spreadsheet` object, where each individual file is a single worksheet within that workbook. For each file that you read, you need to indicate which worksheet index it should be loaded into using the setSheetIndex() method of the $reader, then use the loadIntoExisting() method rather than the load() method to actually read the file into that worksheet. +While you can limit the number of worksheets that are read from a +workbook file using the setLoadSheetsOnly() method, certain readers also +allow you to combine several individual "sheets" from different files +into a single `Spreadsheet` object, where each individual file is a +single worksheet within that workbook. For each file that you read, you +need to indicate which worksheet index it should be loaded into using +the setSheetIndex() method of the \$reader, then use the +loadIntoExisting() method rather than the load() method to actually read +the file into that worksheet. -```php +``` php $inputFileType = 'CSV'; $inputFileNames = array('./sampleData/example1.csv', './sampleData/example2.csv' @@ -732,9 +920,13 @@ foreach($inputFileNames as $sheet => $inputFileName) { ->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME)); } ``` - > See Examples/Reader/exampleReader13.php for a working example of this code. -Note that using the same sheet index for multiple sheets won't append files into the same sheet, but overwrite the results of the previous load. You cannot load multiple CSV files into the same worksheet. +> See Examples/Reader/exampleReader13.php for a working example of this +> code. + +Note that using the same sheet index for multiple sheets won't append +files into the same sheet, but overwrite the results of the previous +load. You cannot load multiple CSV files into the same worksheet. Combining Multiple Files into a Single Spreadsheet Object applies to: @@ -744,11 +936,20 @@ Xlsx | NO | Xls | NO | Excel2003XML | NO | Ods | NO | SYLK | YES | Gnumeric | NO | CSV | YES | HTML | NO -### Combining Read Filters with the setSheetIndex() method to split a large CSV file across multiple Worksheets +### Combining Read Filters with the setSheetIndex() method to split a large CSV file across multiple Worksheets -An Xls BIFF .xls file is limited to 65536 rows in a worksheet, while the Xlsx Microsoft Office Open XML SpreadsheetML .xlsx file is limited to 1,048,576 rows in a worksheet; but a CSV file is not limited other than by available disk space. This means that we wouldn’t ordinarily be able to read all the rows from a very large CSV file that exceeded those limits, and save it as an Xls or Xlsx file. However, by using Read Filters to read the CSV file in “chunks” (using the chunkReadFilter Class that we defined in section REF _Ref275604563 \r \p 5.3 above), and the setSheetIndex() method of the $reader, we can split the CSV file across several individual worksheets. +An Xls BIFF .xls file is limited to 65536 rows in a worksheet, while the +Xlsx Microsoft Office Open XML SpreadsheetML .xlsx file is limited to +1,048,576 rows in a worksheet; but a CSV file is not limited other than +by available disk space. This means that we wouldn’t ordinarily be able +to read all the rows from a very large CSV file that exceeded those +limits, and save it as an Xls or Xlsx file. However, by using Read +Filters to read the CSV file in “chunks” (using the chunkReadFilter +Class that we defined in section REF \_Ref275604563 \r \p 5.3 above), +and the setSheetIndex() method of the \$reader, we can split the CSV +file across several individual worksheets. -```php +``` php $inputFileType = 'CSV'; $inputFileName = './sampleData/example2.csv'; @@ -789,13 +990,22 @@ for ($startRow = 2; $startRow <= 1000000; $startRow += $chunkSize) { $spreadsheet->getActiveSheet()->setTitle('Country Data #'.(++$sheet)); } ``` - > See Examples/Reader/exampleReader14.php for a working example of this code. -This code will read 65,530 rows at a time from the CSV file that we’re loading, and store each "chunk" in a new worksheet. +> See Examples/Reader/exampleReader14.php for a working example of this +> code. -The setContiguous() method for the Reader is important here. It is applicable only when working with a Read Filter, and identifies whether or not the cells should be stored by their position within the CSV file, or their position relative to the filter. +This code will read 65,530 rows at a time from the CSV file that we’re +loading, and store each "chunk" in a new worksheet. -For example, if the filter returned true for cells in the range B2:C3, then with setContiguous set to false (the default) these would be loaded as B2:C3 in the `Spreadsheet` object; but with setContiguous set to true, they would be loaded as A1:B2. +The setContiguous() method for the Reader is important here. It is +applicable only when working with a Read Filter, and identifies whether +or not the cells should be stored by their position within the CSV file, +or their position relative to the filter. + +For example, if the filter returned true for cells in the range B2:C3, +then with setContiguous set to false (the default) these would be loaded +as B2:C3 in the `Spreadsheet` object; but with setContiguous set to +true, they would be loaded as A1:B2. Splitting a single loaded file across multiple worksheets applies to: @@ -807,9 +1017,11 @@ CSV | YES | HTML | NO ### Pipe or Tab Separated Value Files -The CSV loader defaults to loading a file where comma is used as the separator, but you can modify this to load tab- or pipe-separated value files using the setDelimiter() method. +The CSV loader defaults to loading a file where comma is used as the +separator, but you can modify this to load tab- or pipe-separated value +files using the setDelimiter() method. -```php +``` php $inputFileType = 'CSV'; $inputFileName = './sampleData/example1.tsv'; @@ -821,12 +1033,14 @@ $reader->setDelimiter("\t"); /** Load the file to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader15.php for a working example of this code. -In addition to the delimiter, you can also use the following methods to set other attributes for the data load: +> See Examples/Reader/exampleReader15.php for a working example of this +> code. -setEnclosure() | default is " -setLineEnding() | default is PHP_EOL +In addition to the delimiter, you can also use the following methods to +set other attributes for the data load: + +setEnclosure() | default is " setLineEnding() | default is PHP\_EOL setInputEncoding() | default is UTF-8 Setting CSV delimiter applies to: @@ -839,13 +1053,34 @@ CSV | YES | HTML | NO ### A Brief Word about the Advanced Value Binder -When loading data from a file that contains no formatting information, such as a CSV file, then data is read either as strings or numbers (float or integer). This means that PhpSpreadsheet does not automatically recognise dates/times (such as "16-Apr-2009" or "13:30"), booleans ("TRUE" or "FALSE"), percentages ("75%"), hyperlinks ("http://www.phpexcel.net"), etc as anything other than simple strings. However, you can apply additional processing that is executed against these values during the load process within a Value Binder. +When loading data from a file that contains no formatting information, +such as a CSV file, then data is read either as strings or numbers +(float or integer). This means that PhpSpreadsheet does not +automatically recognise dates/times (such as "16-Apr-2009" or "13:30"), +booleans ("TRUE" or "FALSE"), percentages ("75%"), hyperlinks +("http://www.phpexcel.net"), etc as anything other than simple strings. +However, you can apply additional processing that is executed against +these values during the load process within a Value Binder. -A Value Binder is a class that implement the \PhpOffice\PhpSpreadsheet\Cell\IValueBinder interface. It must contain a bindValue() method that accepts a \PhpOffice\PhpSpreadsheet\Cell and a value as arguments, and return a boolean true or false that indicates whether the workbook cell has been populated with the value or not. The Advanced Value Binder implements such a class: amongst other tests, it identifies a string comprising "TRUE" or "FALSE" (based on locale settings) and sets it to a boolean; or a number in scientific format (e.g. "1.234e-5") and converts it to a float; or dates and times, converting them to their Excel timestamp value – before storing the value in the cell object. It also sets formatting for strings that are identified as dates, times or percentages. It could easily be extended to provide additional handling (including text or cell formatting) when it encountered a hyperlink, or HTML markup within a CSV file. +A Value Binder is a class that implement the +\PhpOffice\PhpSpreadsheet\Cell\IValueBinder interface. It must contain a +bindValue() method that accepts a \PhpOffice\PhpSpreadsheet\Cell and a +value as arguments, and return a boolean true or false that indicates +whether the workbook cell has been populated with the value or not. The +Advanced Value Binder implements such a class: amongst other tests, it +identifies a string comprising "TRUE" or "FALSE" (based on locale +settings) and sets it to a boolean; or a number in scientific format +(e.g. "1.234e-5") and converts it to a float; or dates and times, +converting them to their Excel timestamp value – before storing the +value in the cell object. It also sets formatting for strings that are +identified as dates, times or percentages. It could easily be extended +to provide additional handling (including text or cell formatting) when +it encountered a hyperlink, or HTML markup within a CSV file. -So using a Value Binder allows a great deal more flexibility in the loader logic when reading unformatted text files. +So using a Value Binder allows a great deal more flexibility in the +loader logic when reading unformatted text files. -```php +``` php /** Tell PhpSpreadsheet that we want to use the Advanced Value Binder **/ \PhpOffice\PhpSpreadsheet\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); @@ -856,7 +1091,9 @@ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); $reader->setDelimiter("\t"); $spreadsheet = $reader->load($inputFileName); ``` - > See Examples/Reader/exampleReader15.php for a working example of this code. + +> See Examples/Reader/exampleReader15.php for a working example of this +> code. Loading using a Value Binder applies to: @@ -866,15 +1103,18 @@ Xlsx | NO | Xls | NO | Excel2003XML | NO Ods | NO | SYLK | NO | Gnumeric | NO CSV | YES | HTML | YES - - ## Error Handling -Of course, you should always apply some error handling to your scripts as well. PhpSpreadsheet throws exceptions, so you can wrap all your code that accesses the library methods within Try/Catch blocks to trap for any problems that are encountered, and deal with them in an appropriate manner. +Of course, you should always apply some error handling to your scripts +as well. PhpSpreadsheet throws exceptions, so you can wrap all your code +that accesses the library methods within Try/Catch blocks to trap for +any problems that are encountered, and deal with them in an appropriate +manner. -The PhpSpreadsheet Readers throw a \PhpOffice\PhpSpreadsheet\Reader\Exception. +The PhpSpreadsheet Readers throw a +\PhpOffice\PhpSpreadsheet\Reader\Exception. -```php +``` php $inputFileName = './sampleData/example-1.xls'; try { @@ -884,19 +1124,24 @@ try { die('Error loading file: '.$e->getMessage()); } ``` - > See Examples/Reader/exampleReader16.php for a working example of this code. - +> See Examples/Reader/exampleReader16.php for a working example of this +> code. ## Helper Methods -You can retrieve a list of worksheet names contained in a file without loading the whole file by using the Reader’s `listWorksheetNames()` method; similarly, a `listWorksheetInfo()` method will retrieve the dimensions of worksheet in a file without needing to load and parse the whole file. +You can retrieve a list of worksheet names contained in a file without +loading the whole file by using the Reader’s `listWorksheetNames()` +method; similarly, a `listWorksheetInfo()` method will retrieve the +dimensions of worksheet in a file without needing to load and parse the +whole file. ### listWorksheetNames -The `listWorksheetNames()` method returns a simple array listing each worksheet name within the workbook: +The `listWorksheetNames()` method returns a simple array listing each +worksheet name within the workbook: -```php +``` php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); $worksheetNames = $reader->listWorksheetNames($inputFileName); @@ -908,13 +1153,16 @@ foreach ($worksheetNames as $worksheetName) { } echo ''; ``` - > See Examples/Reader/exampleReader18.php for a working example of this code. + +> See Examples/Reader/exampleReader18.php for a working example of this +> code. ### listWorksheetInfo -The `listWorksheetInfo()` method returns a nested array, with each entry listing the name and dimensions for a worksheet: +The `listWorksheetInfo()` method returns a nested array, with each entry +listing the name and dimensions for a worksheet: -```php +``` php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); $worksheetData = $reader->listWorksheetInfo($inputFileName); @@ -931,4 +1179,6 @@ foreach ($worksheetData as $worksheet) { } echo ''; ``` - > See Examples/Reader/exampleReader19.php for a working example of this code. + +> See Examples/Reader/exampleReader19.php for a working example of this +> code. diff --git a/docs/topics/recipes.md b/docs/topics/recipes.md index 713a786e..ab197e9e 100644 --- a/docs/topics/recipes.md +++ b/docs/topics/recipes.md @@ -1,16 +1,26 @@ # Recipes -The following pages offer you some widely-used PhpSpreadsheet recipes. Please note that these do NOT offer complete documentation on specific PhpSpreadsheet API functions, but just a bump to get you started. If you need specific API functions, please refer to the API documentation. +The following pages offer you some widely-used PhpSpreadsheet recipes. +Please note that these do NOT offer complete documentation on specific +PhpSpreadsheet API functions, but just a bump to get you started. If you +need specific API functions, please refer to the API documentation. -For example, REF _Ref191885321 \w \h 4.4.7 REF _Ref191885321 \h Setting a worksheet's page orientation and size covers setting a page orientation to A4. Other paper formats, like US Letter, are not covered in this document, but in the PhpSpreadsheet API documentation. +For example, REF \_Ref191885321 \w \h 4.4.7 REF \_Ref191885321 +\h Setting a worksheet's page orientation and size covers setting a page +orientation to A4. Other paper formats, like US Letter, are not covered +in this document, but in the PhpSpreadsheet API documentation. ## Setting a spreadsheet's metadata -PhpSpreadsheet allows an easy way to set a spreadsheet's metadata, using document property accessors. Spreadsheet metadata can be useful for finding a specific document in a file repository or a document management system. For example Microsoft Sharepoint uses document metadata to search for a specific document in its document lists. +PhpSpreadsheet allows an easy way to set a spreadsheet's metadata, using +document property accessors. Spreadsheet metadata can be useful for +finding a specific document in a file repository or a document +management system. For example Microsoft Sharepoint uses document +metadata to search for a specific document in its document lists. Setting spreadsheet metadata is done as follows: -```php +``` php $spreadsheet->getProperties() ->setCreator("Maarten Balliauw") ->setLastModifiedBy("Maarten Balliauw") @@ -25,29 +35,40 @@ $spreadsheet->getProperties() ## Setting a spreadsheet's active sheet -The following line of code sets the active sheet index to the first sheet: +The following line of code sets the active sheet index to the first +sheet: -```php +``` php $spreadsheet->setActiveSheetIndex(0); ``` You can also set the active sheet by its name/title -```php +``` php $spreadsheet->setActiveSheetIndexByName('DataSheet') ``` -will change the currently active sheet to the worksheet called "DataSheet". +will change the currently active sheet to the worksheet called +"DataSheet". ## Write a date or time into a cell -In Excel, dates and Times are stored as numeric values counting the number of days elapsed since 1900-01-01. For example, the date '2008-12-31' is represented as 39813. You can verify this in Microsoft Office Excel by entering that date in a cell and afterwards changing the number format to 'General' so the true numeric value is revealed. Likewise, '3:15 AM' is represented as 0.135417. +In Excel, dates and Times are stored as numeric values counting the +number of days elapsed since 1900-01-01. For example, the date +'2008-12-31' is represented as 39813. You can verify this in Microsoft +Office Excel by entering that date in a cell and afterwards changing the +number format to 'General' so the true numeric value is revealed. +Likewise, '3:15 AM' is represented as 0.135417. -PhpSpreadsheet works with UST (Universal Standard Time) date and Time values, but does no internal conversions; so it is up to the developer to ensure that values passed to the date/time conversion functions are UST. +PhpSpreadsheet works with UST (Universal Standard Time) date and Time +values, but does no internal conversions; so it is up to the developer +to ensure that values passed to the date/time conversion functions are +UST. -Writing a date value in a cell consists of 2 lines of code. Select the method that suits you the best. Here are some examples: +Writing a date value in a cell consists of 2 lines of code. Select the +method that suits you the best. Here are some examples: -```php +``` php // MySQL-like timestamp '2008-12-31' or date string \PhpOffice\PhpSpreadsheet\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); @@ -74,39 +95,55 @@ $spreadsheet->getActiveSheet()->getStyle('D1') ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH); ``` -The above methods for entering a date all yield the same result. \PhpOffice\PhpSpreadsheet\Style\NumberFormat provides a lot of pre-defined date formats. +The above methods for entering a date all yield the same result. +\PhpOffice\PhpSpreadsheet\Style\NumberFormat provides a lot of +pre-defined date formats. -The \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel() method will also work with a PHP DateTime object. +The \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel() method will also +work with a PHP DateTime object. -Similarly, times (or date and time values) can be entered in the same fashion: just remember to use an appropriate format code. +Similarly, times (or date and time values) can be entered in the same +fashion: just remember to use an appropriate format code. -__Notes:__ +**Notes:** -See section "Using value binders to facilitate data entry" to learn more about the AdvancedValueBinder used in the first example. -Excel can also operate in a 1904-based calendar (default for workbooks saved on Mac). Normally, you do not have to worry about this when using PhpSpreadsheet. +See section "Using value binders to facilitate data entry" to learn more +about the AdvancedValueBinder used in the first example. Excel can also +operate in a 1904-based calendar (default for workbooks saved on Mac). +Normally, you do not have to worry about this when using PhpSpreadsheet. ## Write a formula into a cell -Inside the Excel file, formulas are always stored as they would appear in an English version of Microsoft Office Excel, and PhpSpreadsheet handles all formulae internally in this format. This means that the following rules hold: +Inside the Excel file, formulas are always stored as they would appear +in an English version of Microsoft Office Excel, and PhpSpreadsheet +handles all formulae internally in this format. This means that the +following rules hold: - - Decimal separator is '.' (period) - - Function argument separator is ',' (comma) - - Matrix row separator is ';' (semicolon) - - English function names must be used +- Decimal separator is '.' (period) +- Function argument separator is ',' (comma) +- Matrix row separator is ';' (semicolon) +- English function names must be used -This is regardless of which language version of Microsoft Office Excel may have been used to create the Excel file. +This is regardless of which language version of Microsoft Office Excel +may have been used to create the Excel file. -When the final workbook is opened by the user, Microsoft Office Excel will take care of displaying the formula according the applications language. Translation is taken care of by the application! +When the final workbook is opened by the user, Microsoft Office Excel +will take care of displaying the formula according the applications +language. Translation is taken care of by the application! -The following line of code writes the formula '=IF(C4>500,"profit","loss")' into the cell B8. Note that the formula must start with "=" to make PhpSpreadsheet recognise this as a formula. +The following line of code writes the formula +'=IF(C4>500,"profit","loss")' into the cell B8. Note that the +formula must start with "=" to make PhpSpreadsheet recognise this as a +formula. -```php +``` php $spreadsheet->getActiveSheet()->setCellValue('B8','=IF(C4>500,"profit","loss")'); ``` -If you want to write a string beginning with an "=" character to a cell, then you should use the setCellValueExplicit() method. +If you want to write a string beginning with an "=" character to a +cell, then you should use the setCellValueExplicit() method. -```php +``` php $spreadsheet->getActiveSheet() ->setCellValueExplicit( 'B8', @@ -117,21 +154,24 @@ $spreadsheet->getActiveSheet() A cell's formula can be read again using the following line of code: -```php +``` php $formula = $spreadsheet->getActiveSheet()->getCell('B8')->getValue(); ``` -If you need the calculated value of a cell, use the following code. This is further explained in REF _Ref191885372 \w \h \* MERGEFORMAT 4.4.35. +If you need the calculated value of a cell, use the following code. This +is further explained in REF \_Ref191885372 \w \h \* MERGEFORMAT 4.4.35. -```php +``` php $value = $spreadsheet->getActiveSheet()->getCell('B8')->getCalculatedValue(); ``` ## Locale Settings for Formulae -Some localisation elements have been included in PhpSpreadsheet. You can set a locale by changing the settings. To set the locale to Russian you would use: +Some localisation elements have been included in PhpSpreadsheet. You can +set a locale by changing the settings. To set the locale to Russian you +would use: -```php +``` php $locale = 'ru'; $validLocale = \PhpOffice\PhpSpreadsheet\Settings::setLocale($locale); if (!$validLocale) { @@ -139,24 +179,29 @@ if (!$validLocale) { } ``` -If Russian language files aren't available, the `setLocale()` method will return an error, and English settings will be used throughout. +If Russian language files aren't available, the `setLocale()` method +will return an error, and English settings will be used throughout. -Once you have set a locale, you can translate a formula from its internal English coding. +Once you have set a locale, you can translate a formula from its +internal English coding. -```php +``` php $formula = $spreadsheet->getActiveSheet()->getCell('B8')->getValue(); $translatedFormula = \PhpOffice\PhpSpreadsheet\Calculation::getInstance()->_translateFormulaToLocale($formula); ``` -You can also create a formula using the function names and argument separators appropriate to the defined locale; then translate it to English before setting the cell value: +You can also create a formula using the function names and argument +separators appropriate to the defined locale; then translate it to +English before setting the cell value: -```php -$formula = '=????360(????(2010;2;5);????(2010;12;31);??????)'; +``` php +$formula = '=ДНЕЙ360(ДАТА(2010;2;5);ДАТА(2010;12;31);ИСТИНА)'; $internalFormula = \PhpOffice\PhpSpreadsheet\Calculation::getInstance()->translateFormulaToEnglish($formula); $spreadsheet->getActiveSheet()->setCellValue('B8',$internalFormula); ``` -Currently, formula translation only translates the function names, the constants TRUE and FALSE, and the function argument separators. +Currently, formula translation only translates the function names, the +constants TRUE and FALSE, and the function argument separators. At present, the following locale settings are supported: @@ -175,30 +220,34 @@ Norwegian | Norsk | no Polish | Jezyk polski | pl Portuguese | Português | pt Brazilian Portuguese | Português Brasileiro | pt_br -Russian | ??????? ???? | ru +Russian | русский язык | ru Swedish | Svenska | sv Turkish | Türkçe | tr ## Write a newline character "\n" in a cell (ALT+"Enter") -In Microsoft Office Excel you get a line break in a cell by hitting ALT+"Enter". When you do that, it automatically turns on "wrap text" for the cell. +In Microsoft Office Excel you get a line break in a cell by hitting +ALT+"Enter". When you do that, it automatically turns on "wrap text" for +the cell. Here is how to achieve this in PhpSpreadsheet: -```php +``` php $spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld"); $spreadsheet->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true); ``` -__Tip__ +**Tip** Read more about formatting cells using getStyle() elsewhere. -__Tip__ +**Tip** -AdvancedValuebinder.php automatically turns on "wrap text" for the cell when it sees a newline character in a string that you are inserting in a cell. Just like Microsoft Office Excel. Try this: +AdvancedValuebinder.php automatically turns on "wrap text" for the cell +when it sees a newline character in a string that you are inserting in a +cell. Just like Microsoft Office Excel. Try this: -```php +``` php \PhpOffice\PhpSpreadsheet\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() ); $spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld"); @@ -208,9 +257,11 @@ Read more about AdvancedValueBinder.php elsewhere. ## Explicitly set a cell's datatype -You can set a cell's datatype explicitly by using the cell's setValueExplicit method, or the setCellValueExplicit method of a worksheet. Here's an example: +You can set a cell's datatype explicitly by using the cell's +setValueExplicit method, or the setCellValueExplicit method of a +worksheet. Here's an example: -```php +``` php $spreadsheet->getActiveSheet()->getCell('A1') ->setValueExplicit( '25', @@ -222,14 +273,15 @@ $spreadsheet->getActiveSheet()->getCell('A1') You can make a cell a clickable URL by setting its hyperlink property: -```php +``` php $spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net'); $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('http://www.phpexcel.net'); ``` -If you want to make a hyperlink to another worksheet/cell, use the following code: +If you want to make a hyperlink to another worksheet/cell, use the +following code: -```php +``` php $spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net'); $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl("sheet://'Sheetname'!A1"); ``` @@ -238,24 +290,28 @@ $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl("sheet:// ### Setting a worksheet's page orientation and size -Setting a worksheet's page orientation and size can be done using the following lines of code: +Setting a worksheet's page orientation and size can be done using the +following lines of code: -```php +``` php $spreadsheet->getActiveSheet()->getPageSetup() ->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE); $spreadsheet->getActiveSheet()->getPageSetup() ->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4); ``` -Note that there are additional page settings available. Please refer to the API documentation for all possible options. +Note that there are additional page settings available. Please refer to +the API documentation for all possible options. ### Page Setup: Scaling options -The page setup scaling options in PhpSpreadsheet relate directly to the scaling options in the "Page Setup" dialog as shown in the illustration. +The page setup scaling options in PhpSpreadsheet relate directly to the +scaling options in the "Page Setup" dialog as shown in the illustration. -Default values in PhpSpreadsheet correspond to default values in MS Office Excel as shown in illustration +Default values in PhpSpreadsheet correspond to default values in MS +Office Excel as shown in illustration -![08-page-setup-scaling-options.png](./images/08-page-setup-scaling-options.png "") +![08-page-setup-scaling-options.png](./images/08-page-setup-scaling-options.png) method | initial value | calling method will trigger | Note --------------------|:-------------:|-----------------------------|------ @@ -268,20 +324,23 @@ setFitToHeight(...) | 1 | setFitToPage(TRUE) | value 0 mean Here is how to fit to 1 page wide by infinite pages tall: -```php +``` php $spreadsheet->getActiveSheet()->getPageSetup()->setFitToWidth(1); $spreadsheet->getActiveSheet()->getPageSetup()->setFitToHeight(0); ``` -As you can see, it is not necessary to call setFitToPage(TRUE) since setFitToWidth(...) and setFitToHeight(...) triggers this. +As you can see, it is not necessary to call setFitToPage(TRUE) since +setFitToWidth(...) and setFitToHeight(...) triggers this. -If you use setFitToWidth() you should in general also specify setFitToHeight() explicitly like in the example. Be careful relying on the initial values. +If you use setFitToWidth() you should in general also specify +setFitToHeight() explicitly like in the example. Be careful relying on +the initial values. ### Page margins To set page margins for a worksheet, use this code: -```php +``` php $spreadsheet->getActiveSheet()->getPageMargins()->setTop(1); $spreadsheet->getActiveSheet()->getPageMargins()->setRight(0.75); $spreadsheet->getActiveSheet()->getPageMargins()->setLeft(0.75); @@ -290,84 +349,86 @@ $spreadsheet->getActiveSheet()->getPageMargins()->setBottom(1); Note that the margin values are specified in inches. -![08-page-setup-margins.png](./images/08-page-setup-margins.png "") +![08-page-setup-margins.png](./images/08-page-setup-margins.png) ### Center a page horizontally/vertically -To center a page horizontally/vertically, you can use the following code: +To center a page horizontally/vertically, you can use the following +code: -```php +``` php $spreadsheet->getActiveSheet()->getPageSetup()->setHorizontalCentered(true); $spreadsheet->getActiveSheet()->getPageSetup()->setVerticalCentered(false); ``` ### Setting the print header and footer of a worksheet -Setting a worksheet's print header and footer can be done using the following lines of code: +Setting a worksheet's print header and footer can be done using the +following lines of code: -```php +``` php $spreadsheet->getActiveSheet()->getHeaderFooter() ->setOddHeader('&C&HPlease treat this document as confidential!'); $spreadsheet->getActiveSheet()->getHeaderFooter() ->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N'); ``` -Substitution and formatting codes (starting with &) can be used inside headers and footers. There is no required order in which these codes must appear. +Substitution and formatting codes (starting with &) can be used inside +headers and footers. There is no required order in which these codes +must appear. -The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again: +The first occurrence of the following codes turns the formatting ON, the +second occurrence turns it OFF again: - - Strikethrough - - Superscript - - Subscript +- Strikethrough +- Superscript +- Subscript -Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored, while the first is ON. +Superscript and subscript cannot both be ON at same time. Whichever +comes first wins and the other is ignored, while the first is ON. The following codes are supported by Xlsx: -Code | Meaning ------------------------|----------- -&L | Code for "left section" (there are three header / footer locations, "left", "center", and "right"). When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the left section. -&P | Code for "current page #" -&N | Code for "total pages" -&font size | Code for "text font size", where font size is a font size in points. -&K | Code for "text font color" - RGB Color is specified as RRGGBB Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade value, NN is the tint/shade value. -&S | Code for "text strikethrough" on / off -&X | Code for "text super script" on / off -&Y | Code for "text subscript" on / off -&C | Code for "center section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the center section. -&D | Code for "date" -&T | Code for "time" -&G | Code for "picture as background" - Please make sure to add the image to the header/footer[^print-footer-image-footnote] -&U | Code for "text single underline" -&E | Code for "double underline" -&R | Code for "right section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the right section. -&Z | Code for "this workbook's file path" -&F | Code for "this workbook's file name" -&A | Code for "sheet tab name" -&+ | Code for add to page # -&- | Code for subtract from page # -&"font name,font type" | Code for "text font name" and "text font type", where font name and font type are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font name, it means "none specified". Both of font name and font type can be localized values. -&"-,Bold" | Code for "bold font style" -&B | Code for "bold font style" -&"-,Regular" | Code for "regular font style" -&"-,Italic" | Code for "italic font style" -&I | Code for "italic font style" -&"-,Bold Italic" | Code for "bold italic font style" -&O | Code for "outline style" -&H | Code for "shadow style" +Code | Meaning +-------------------------|----------- +`&L` | Code for "left section" (there are three header / footer locations, "left", "center", and "right"). When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the left section. +`&P` | Code for "current page #" +`&N` | Code for "total pages" +`&font size` | Code for "text font size", where font size is a font size in points. +`&K` | Code for "text font color" - RGB Color is specified as RRGGBB Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade value, NN is the tint/shade value. +`&S` | Code for "text strikethrough" on / off +`&X` | Code for "text super script" on / off +`&Y` | Code for "text subscript" on / off +`&C` | Code for "center section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the center section. +`&D` | Code for "date" +`&T` | Code for "time" +`&G` | Code for "picture as background" - Please make sure to add the image to the header/footer (see Tip for picture) +`&U` | Code for "text single underline" +`&E` | Code for "double underline" +`&R` | Code for "right section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the right section. +`&Z` | Code for "this workbook's file path" +`&F` | Code for "this workbook's file name" +`&A` | Code for "sheet tab name" +`&+` | Code for add to page # +`&-` | Code for subtract from page # +`&"font name,font type"` | Code for "text font name" and "text font type", where font name and font type are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font name, it means "none specified". Both of font name and font type can be localized values. +`&"-,Bold"` | Code for "bold font style" +`&B` | Code for "bold font style" +`&"-,Regular"` | Code for "regular font style" +`&"-,Italic"` | Code for "italic font style" +`&I` | Code for "italic font style" +`&"-,Bold Italic"` | Code for "bold italic font style" +`&O` | Code for "outline style" +`&H` | Code for "shadow style" - [^print-footer-image-footnote]: z -```php -$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing(); -$drawing->setName('PhpSpreadsheet logo'); -$drawing->setPath('./images/PhpSpreadsheet_logo.png'); -$drawing->setHeight(36); -$spreadsheet->getActiveSheet()->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT); -``` +**Tip** -__Tip__ - -The above table of codes may seem overwhelming first time you are trying to figure out how to write some header or footer. Luckily, there is an easier way. Let Microsoft Office Excel do the work for you.For example, create in Microsoft Office Excel an xlsx file where you insert the header and footer as desired using the programs own interface. Save file as test.xlsx. Now, take that file and read off the values using PhpSpreadsheet as follows: +The above table of codes may seem overwhelming first time you are trying to +figure out how to write some header or footer. Luckily, there is an easier way. +Let Microsoft Office Excel do the work for you.For example, create in Microsoft + Office Excel an xlsx file where you insert the header and footer as desired +using the programs own interface. Save file as test.xlsx. Now, take that file +and read off the values using PhpSpreadsheet as follows: ```php $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('test.xlsx'); @@ -379,19 +440,33 @@ var_dump($worksheet->getHeaderFooter()->getOddHeader()); var_dump($worksheet->getHeaderFooter()->getEvenHeader()); ``` -That reveals the codes for the even/odd header and footer. Experienced users may find it easier to rename test.xlsx to test.zip, unzip it, and inspect directly the contents of the relevant xl/worksheets/sheetX.xml to find the codes for header/footer. +That reveals the codes for the even/odd header and footer. Experienced +users may find it easier to rename test.xlsx to test.zip, unzip it, and +inspect directly the contents of the relevant xl/worksheets/sheetX.xml +to find the codes for header/footer. + +**Tip for picture** + +```php +$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing(); +$drawing->setName('PhpSpreadsheet logo'); +$drawing->setPath('./images/PhpSpreadsheet_logo.png'); +$drawing->setHeight(36); +$spreadsheet->getActiveSheet()->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT); +``` ### Setting printing breaks on a row or column -To set a print break, use the following code, which sets a row break on row 10. +To set a print break, use the following code, which sets a row break on +row 10. -```php +``` php $spreadsheet->getActiveSheet()->setBreak( 'A10' , \PhpOffice\PhpSpreadsheet\Worksheet::BREAK_ROW ); ``` The following line of code sets a print break on column D: -```php +``` php $spreadsheet->getActiveSheet()->setBreak( 'D10' , \PhpOffice\PhpSpreadsheet\Worksheet::BREAK_COLUMN ); ``` @@ -399,13 +474,15 @@ $spreadsheet->getActiveSheet()->setBreak( 'D10' , \PhpOffice\PhpSpreadsheet\Work To show/hide gridlines when printing, use the following code: -$spreadsheet->getActiveSheet()->setShowGridlines(true); +\$spreadsheet->getActiveSheet()->setShowGridlines(true); ### Setting rows/columns to repeat at top/left -PhpSpreadsheet can repeat specific rows/cells at top/left of a page. The following code is an example of how to repeat row 1 to 5 on each printed page of a specific worksheet: +PhpSpreadsheet can repeat specific rows/cells at top/left of a page. The +following code is an example of how to repeat row 1 to 5 on each printed +page of a specific worksheet: -```php +``` php $spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5); ``` @@ -413,13 +490,13 @@ $spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEn To specify a worksheet's printing area, use the following code: -```php +``` php $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5'); ``` There can also be multiple printing areas in a single worksheet: -```php +``` php $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5,G4:M20'); ``` @@ -427,9 +504,12 @@ $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5,G4:M20'); ### Formatting cells -A cell can be formatted with font, border, fill, ... style information. For example, one can set the foreground colour of a cell to red, aligned to the right, and the border to black and thick border style. Let's do that on cell B2: +A cell can be formatted with font, border, fill, ... style information. +For example, one can set the foreground colour of a cell to red, aligned +to the right, and the border to black and thick border style. Let's do +that on cell B2: -```php +``` php $spreadsheet->getActiveSheet()->getStyle('B2') ->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED); $spreadsheet->getActiveSheet()->getStyle('B2') @@ -448,20 +528,25 @@ $spreadsheet->getActiveSheet()->getStyle('B2') ->getFill()->getStartColor()->setARGB('FFFF0000'); ``` -`getStyle()` also accepts a cell range as a parameter. For example, you can set a red background color on a range of cells: +`getStyle()` also accepts a cell range as a parameter. For example, you +can set a red background color on a range of cells: -```php +``` php $spreadsheet->getActiveSheet()->getStyle('B3:B7')->getFill() ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID) ->getStartColor()->setARGB('FFFF0000'); ``` -__Tip__ -It is recommended to style many cells at once, using e.g. getStyle('A1:M500'), rather than styling the cells individually in a loop. This is much faster compared to looping through cells and styling them individually. +**Tip** It is recommended to style many cells at once, using e.g. +getStyle('A1:M500'), rather than styling the cells individually in a +loop. This is much faster compared to looping through cells and styling +them individually. -There is also an alternative manner to set styles. The following code sets a cell's style to font bold, alignment right, top border thin and a gradient fill: +There is also an alternative manner to set styles. The following code +sets a cell's style to font bold, alignment right, top border thin and a +gradient fill: -```php +``` php $styleArray = array( 'font' => array( 'bold' => true, @@ -491,94 +576,122 @@ $spreadsheet->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray); Or with a range of cells: -```php +``` php $spreadsheet->getActiveSheet()->getStyle('B3:B7')->applyFromArray($styleArray); ``` -This alternative method using arrays should be faster in terms of execution whenever you are setting more than one style property. But the difference may barely be measurable unless you have many different styles in your workbook. +This alternative method using arrays should be faster in terms of +execution whenever you are setting more than one style property. But the +difference may barely be measurable unless you have many different +styles in your workbook. -Prior to PHPExcel 1.7.0 duplicateStyleArray() was the recommended method for styling a cell range, but this method has now been deprecated since getStyle() has started to accept a cell range. +Prior to PHPExcel 1.7.0 duplicateStyleArray() was the recommended method +for styling a cell range, but this method has now been deprecated since +getStyle() has started to accept a cell range. ### Number formats -You often want to format numbers in Excel. For example you may want a thousands separator plus a fixed number of decimals after the decimal separator. Or perhaps you want some numbers to be zero-padded. +You often want to format numbers in Excel. For example you may want a +thousands separator plus a fixed number of decimals after the decimal +separator. Or perhaps you want some numbers to be zero-padded. -In Microsoft Office Excel you may be familiar with selecting a number format from the "Format Cells" dialog. Here there are some predefined number formats available including some for dates. The dialog is designed in a way so you don't have to interact with the underlying raw number format code unless you need a custom number format. +In Microsoft Office Excel you may be familiar with selecting a number +format from the "Format Cells" dialog. Here there are some predefined +number formats available including some for dates. The dialog is +designed in a way so you don't have to interact with the underlying raw +number format code unless you need a custom number format. -In PhpSpreadsheet, you can also apply various predefined number formats. Example: +In PhpSpreadsheet, you can also apply various predefined number formats. +Example: -```php +``` php $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat() ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1); ``` -This will format a number e.g. 1587.2 so it shows up as 1,587.20 when you open the workbook in MS Office Excel. (Depending on settings for decimal and thousands separators in Microsoft Office Excel it may show up as 1.587,20) +This will format a number e.g. 1587.2 so it shows up as 1,587.20 when +you open the workbook in MS Office Excel. (Depending on settings for +decimal and thousands separators in Microsoft Office Excel it may show +up as 1.587,20) You can achieve exactly the same as the above by using this: -```php +``` php $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat() ->setFormatCode('#,##0.00'); ``` -In Microsoft Office Excel, as well as in PhpSpreadsheet, you will have to interact with raw number format codes whenever you need some special custom number format. Example: +In Microsoft Office Excel, as well as in PhpSpreadsheet, you will have +to interact with raw number format codes whenever you need some special +custom number format. Example: -```php +``` php $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat() ->setFormatCode('[Blue][>=3000]$#,##0;[Red][<0]$#,##0;$#,##0'); ``` -Another example is when you want numbers zero-padded with leading zeros to a fixed length: +Another example is when you want numbers zero-padded with leading zeros +to a fixed length: -```php +``` php $spreadsheet->getActiveSheet()->getCell('A1')->setValue(19); $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat() ->setFormatCode('0000'); // will show as 0019 in Excel ``` -__Tip__ -The rules for composing a number format code in Excel can be rather complicated. Sometimes you know how to create some number format in Microsoft Office Excel, but don't know what the underlying number format code looks like. How do you find it? +**Tip** The rules for composing a number format code in Excel can be +rather complicated. Sometimes you know how to create some number format +in Microsoft Office Excel, but don't know what the underlying number +format code looks like. How do you find it? -The readers shipped with PhpSpreadsheet come to the rescue. Load your template workbook using e.g. Xlsx reader to reveal the number format code. Example how read a number format code for cell A1: +The readers shipped with PhpSpreadsheet come to the rescue. Load your +template workbook using e.g. Xlsx reader to reveal the number format +code. Example how read a number format code for cell A1: -```php +``` php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $spreadsheet = $reader->load('template.xlsx'); var_dump($spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()->getFormatCode()); ``` -Advanced users may find it faster to inspect the number format code directly by renaming template.xlsx to template.zip, unzipping, and looking for the relevant piece of XML code holding the number format code in *xl/styles.xml*. +Advanced users may find it faster to inspect the number format code +directly by renaming template.xlsx to template.zip, unzipping, and +looking for the relevant piece of XML code holding the number format +code in *xl/styles.xml*. ### Alignment and wrap text Let's set vertical alignment to the top for cells A1:D4 -```php +``` php $spreadsheet->getActiveSheet()->getStyle('A1:D4') ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP); ``` Here is how to achieve wrap text: -```php +``` php $spreadsheet->getActiveSheet()->getStyle('A1:D4') ->getAlignment()->setWrapText(true); ``` ### Setting the default style of a workbook -It is possible to set the default style of a workbook. Let's set the default font to Arial size 8: +It is possible to set the default style of a workbook. Let's set the +default font to Arial size 8: -```php +``` php $spreadsheet->getDefaultStyle()->getFont()->setName('Arial'); $spreadsheet->getDefaultStyle()->getFont()->setSize(8); ``` ### Styling cell borders -In PhpSpreadsheet it is easy to apply various borders on a rectangular selection. Here is how to apply a thick red border outline around cells B2:G8. +In PhpSpreadsheet it is easy to apply various borders on a rectangular +selection. Here is how to apply a thick red border outline around cells +B2:G8. -```php +``` php $styleArray = array( 'borders' => array( 'outline' => array( @@ -591,41 +704,54 @@ $styleArray = array( $worksheet->getStyle('B2:G8')->applyFromArray($styleArray); ``` -In Microsoft Office Excel, the above operation would correspond to selecting the cells B2:G8, launching the style dialog, choosing a thick red border, and clicking on the "Outline" border component. +In Microsoft Office Excel, the above operation would correspond to +selecting the cells B2:G8, launching the style dialog, choosing a thick +red border, and clicking on the "Outline" border component. -Note that the border outline is applied to the rectangular selection B2:G8 as a whole, not on each cell individually. +Note that the border outline is applied to the rectangular selection +B2:G8 as a whole, not on each cell individually. -You can achieve any border effect by using just the 5 basic borders and operating on a single cell at a time: +You can achieve any border effect by using just the 5 basic borders and +operating on a single cell at a time: -- left -- right -- top -- bottom -- diagonal - -Additional shortcut borders come in handy like in the example above. These are the shortcut borders available: - -- allborders -- outline -- inside -- vertical -- horizontal +- left +- right +- top +- bottom +- diagonal +Additional shortcut borders come in handy like in the example above. +These are the shortcut borders available: +- allborders +- outline +- inside +- vertical +- horizontal An overview of all border shortcuts can be seen in the following image: -![08-styling-border-options.png](./images/08-styling-border-options.png "") +![08-styling-border-options.png](./images/08-styling-border-options.png) -If you simultaneously set e.g. allborders and vertical, then we have "overlapping" borders, and one of the components has to win over the other where there is border overlap. In PhpSpreadsheet, from weakest to strongest borders, the list is as follows: allborders, outline/inside, vertical/horizontal, left/right/top/bottom/diagonal. +If you simultaneously set e.g. allborders and vertical, then we have +"overlapping" borders, and one of the components has to win over the +other where there is border overlap. In PhpSpreadsheet, from weakest to +strongest borders, the list is as follows: allborders, outline/inside, +vertical/horizontal, left/right/top/bottom/diagonal. -This border hierarchy can be utilized to achieve various effects in an easy manner. +This border hierarchy can be utilized to achieve various effects in an +easy manner. ### Valid array keys for style applyFromArray() -The following table lists the valid array keys for \PhpOffice\PhpSpreadsheet\Style applyFromArray() classes. If the "Maps to property" column maps a key to a setter, the value provided for that key will be applied directly. If the "Maps to property" column maps a key to a getter, the value provided for that key will be applied as another style array. +The following table lists the valid array keys for +\PhpOffice\PhpSpreadsheet\Style applyFromArray() classes. If the "Maps +to property" column maps a key to a setter, the value provided for that +key will be applied directly. If the "Maps to property" column maps a +key to a getter, the value provided for that key will be applied as +another style array. -__\PhpOffice\PhpSpreadsheet\Style__ +**\PhpOffice\PhpSpreadsheet\Style** Array key | Maps to property -------------|------------------- @@ -636,8 +762,7 @@ alignment | getAlignment() numberformat | getNumberFormat() protection | getProtection() - -__\PhpOffice\PhpSpreadsheet\Style\Fill__ +**\PhpOffice\PhpSpreadsheet\Style\Fill** Array key | Maps to property -----------|------------------- @@ -648,7 +773,7 @@ endcolor | getEndColor() color | getStartColor() -__\PhpOffice\PhpSpreadsheet\Style\Font__ +**\PhpOffice\PhpSpreadsheet\Style\Font** Array key | Maps to property ------------|------------------- @@ -662,8 +787,7 @@ size | setSize() superScript | setSuperScript() subScript | setSubScript() - -__\PhpOffice\PhpSpreadsheet\Style\Borders__ +**\PhpOffice\PhpSpreadsheet\Style\Borders** Array key | Maps to property ------------------|------------------- @@ -678,16 +802,14 @@ horizontal | getHorizontal() diagonaldirection | setDiagonalDirection() outline | setOutline() - -__\PhpOffice\PhpSpreadsheet\Style\Border__ +**\PhpOffice\PhpSpreadsheet\Style\Border** Array key | Maps to property ----------|------------------- style | setBorderStyle() color | getColor() - -__\PhpOffice\PhpSpreadsheet\Style\Alignment__ +**\PhpOffice\PhpSpreadsheet\Style\Alignment** Array key | Maps to property ------------|------------------- @@ -698,30 +820,29 @@ wrap | setWrapText() shrinkToFit | setShrinkToFit() indent | setIndent() - -__\PhpOffice\PhpSpreadsheet\Style\NumberFormat__ +**\PhpOffice\PhpSpreadsheet\Style\NumberFormat** Array key | Maps to property ----------|------------------- code | setFormatCode() - -__\PhpOffice\PhpSpreadsheet\Style\Protection__ +**\PhpOffice\PhpSpreadsheet\Style\Protection** Array key | Maps to property ----------|------------------- locked | setLocked() hidden | setHidden() - - ## Conditional formatting a cell -A cell can be formatted conditionally, based on a specific rule. For example, one can set the foreground colour of a cell to red if its value is below zero, and to green if its value is zero or more. +A cell can be formatted conditionally, based on a specific rule. For +example, one can set the foreground colour of a cell to red if its value +is below zero, and to green if its value is zero or more. -One can set a conditional style ruleset to a cell using the following code: +One can set a conditional style ruleset to a cell using the following +code: -```php +``` php $conditional1 = new \PhpOffice\PhpSpreadsheet\Style\Conditional(); $conditional1->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS); $conditional1->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_LESSTHAN); @@ -743,9 +864,10 @@ array_push($conditionalStyles, $conditional2); $spreadsheet->getActiveSheet()->getStyle('B2')->setConditionalStyles($conditionalStyles); ``` -If you want to copy the ruleset to other cells, you can duplicate the style object: +If you want to copy the ruleset to other cells, you can duplicate the +style object: -```php +``` php $spreadsheet->getActiveSheet() ->duplicateStyle( $spreadsheet->getActiveSheet()->getStyle('B2'), @@ -755,9 +877,10 @@ $spreadsheet->getActiveSheet() ## Add a comment to a cell -To add a comment to a cell, use the following code. The example below adds a comment to cell E11: +To add a comment to a cell, use the following code. The example below +adds a comment to cell E11: -```php +``` php $spreadsheet->getActiveSheet() ->getComment('E11') ->setAuthor('Mark Baker'); @@ -773,26 +896,33 @@ $spreadsheet->getActiveSheet() ->getText()->createTextRun('Total amount on the current invoice, excluding VAT.'); ``` -![08-cell-comment.png](./images/08-cell-comment.png "") +![08-cell-comment.png](./images/08-cell-comment.png) ## Apply autofilter to a range of cells To apply an autofilter to a range of cells, use the following code: -```php +``` php $spreadsheet->getActiveSheet()->setAutoFilter('A1:C9'); ``` -__Make sure that you always include the complete filter range!__ -Excel does support setting only the captionrow, but that's __not__ a best practice... +**Make sure that you always include the complete filter range!** Excel +does support setting only the captionrow, but that's **not** a best +practice... ## Setting security on a spreadsheet -Excel offers 3 levels of "protection": document security, sheet security and cell security. +Excel offers 3 levels of "protection": document security, sheet security +and cell security. -Document security allows you to set a password on a complete spreadsheet, allowing changes to be made only when that password is entered.Worksheet security offers other security options: you can disallow inserting rows on a specific sheet, disallow sorting, ... Cell security offers the option to lock/unlock a cell as well as show/hide the internal formulaAn example on setting document security: +Document security allows you to set a password on a complete +spreadsheet, allowing changes to be made only when that password is +entered.Worksheet security offers other security options: you can +disallow inserting rows on a specific sheet, disallow sorting, ... Cell +security offers the option to lock/unlock a cell as well as show/hide +the internal formulaAn example on setting document security: -```php +``` php $spreadsheet->getSecurity()->setLockWindows(true); $spreadsheet->getSecurity()->setLockStructure(true); $spreadsheet->getSecurity()->setWorkbookPassword("PhpSpreadsheet"); @@ -800,7 +930,7 @@ $spreadsheet->getSecurity()->setWorkbookPassword("PhpSpreadsheet"); An example on setting worksheet security: -```php +``` php $spreadsheet->getActiveSheet() ->getProtection()->setPassword('PhpSpreadsheet'); $spreadsheet->getActiveSheet() @@ -815,25 +945,31 @@ $spreadsheet->getActiveSheet() An example on setting cell security: -```php +``` php $spreadsheet->getActiveSheet()->getStyle('B1') ->getProtection() ->setLocked(\PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_UNPROTECTED); ``` -__Make sure you enable worksheet protection if you need any of the worksheet protection features!__ This can be done using the following code: +**Make sure you enable worksheet protection if you need any of the +worksheet protection features!** This can be done using the following +code: -```php +``` php $spreadsheet->getActiveSheet()->getProtection()->setSheet(true); ``` ## Setting data validation on a cell -Data validation is a powerful feature of Xlsx. It allows to specify an input filter on the data that can be inserted in a specific cell. This filter can be a range (i.e. value must be between 0 and 10), a list (i.e. value must be picked from a list), ... +Data validation is a powerful feature of Xlsx. It allows to specify an +input filter on the data that can be inserted in a specific cell. This +filter can be a range (i.e. value must be between 0 and 10), a list +(i.e. value must be picked from a list), ... -The following piece of code only allows numbers between 10 and 20 to be entered in cell B3: +The following piece of code only allows numbers between 10 and 20 to be +entered in cell B3: -```php +``` php $validation = $spreadsheet->getActiveSheet()->getCell('B3') ->getDataValidation(); $validation->setType( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_WHOLE ); @@ -849,9 +985,10 @@ $validation->setFormula1(10); $validation->setFormula2(20); ``` -The following piece of code only allows an item picked from a list of data to be entered in cell B3: +The following piece of code only allows an item picked from a list of +data to be entered in cell B3: -```php +``` php $validation = $spreadsheet->getActiveSheet()->getCell('B5') ->getDataValidation(); $validation->setType( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_LIST ); @@ -867,13 +1004,21 @@ $validation->setPrompt('Please pick a value from the drop-down list.'); $validation->setFormula1('"Item A,Item B,Item C"'); ``` -When using a data validation list like above, make sure you put the list between " and " and that you split the items with a comma (,). +When using a data validation list like above, make sure you put the list +between " and " and that you split the items with a comma (,). -It is important to remember that any string participating in an Excel formula is allowed to be maximum 255 characters (not bytes). This sets a limit on how many items you can have in the string "Item A,Item B,Item C". Therefore it is normally a better idea to type the item values directly in some cell range, say A1:A3, and instead use, say, $validation->setFormula1('Sheet!$A$1:$A$3');. Another benefit is that the item values themselves can contain the comma "," character itself. +It is important to remember that any string participating in an Excel +formula is allowed to be maximum 255 characters (not bytes). This sets a +limit on how many items you can have in the string "Item A,Item B,Item +C". Therefore it is normally a better idea to type the item values +directly in some cell range, say A1:A3, and instead use, say, +$validation->setFormula1('Sheet!$A$1:$A\$3');. Another benefit is that +the item values themselves can contain the comma "," character itself. -If you need data validation on multiple cells, one can clone the ruleset: +If you need data validation on multiple cells, one can clone the +ruleset: -```php +``` php $spreadsheet->getActiveSheet()->getCell('B8')->setDataValidation(clone $validation); ``` @@ -881,25 +1026,46 @@ $spreadsheet->getActiveSheet()->getCell('B8')->setDataValidation(clone $validati A column's width can be set using the following code: -```php +``` php $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(12); ``` -If you want PhpSpreadsheet to perform an automatic width calculation, use the following code. PhpSpreadsheet will approximate the column with to the width of the widest column value. +If you want PhpSpreadsheet to perform an automatic width calculation, +use the following code. PhpSpreadsheet will approximate the column with +to the width of the widest column value. -```php +``` php $spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); ``` -![08-column-width.png](./images/08-column-width.png "") +![08-column-width.png](./images/08-column-width.png) -The measure for column width in PhpSpreadsheet does __not__ correspond exactly to the measure you may be used to in Microsoft Office Excel. Column widths are difficult to deal with in Excel, and there are several measures for the column width.1) __Inner width in character units__ (e.g. 8.43 this is probably what you are familiar with in Excel)2) __Full width in pixels__ (e.g. 64 pixels)3) __Full width in character units__ (e.g. 9.140625, value -1 indicates unset width)__PHPExcel always operates with 3) "Full width in character units"__ which is in fact the only value that is stored in any Excel file, hence the most reliable measure. Unfortunately, __Microsoft ____Office ____Excel does not present you with this ____measure__. Instead measures 1) and 2) are computed by the application when the file is opened and these values are presented in various dialogues and tool tips.The character width unit is the width of a '0' (zero) glyph in the workbooks default font. Therefore column widths measured in character units in two different workbooks can only be compared if they have the same default workbook font.If you have some Excel file and need to know the column widths in measure 3), you can read the Excel file with PhpSpreadsheet and echo the retrieved values. +The measure for column width in PhpSpreadsheet does **not** correspond +exactly to the measure you may be used to in Microsoft Office Excel. +Column widths are difficult to deal with in Excel, and there are several +measures for the column width.1) **Inner width in character units** +(e.g. 8.43 this is probably what you are familiar with in Excel)2) +**Full width in pixels** (e.g. 64 pixels)3) **Full width in character +units** (e.g. 9.140625, value -1 indicates unset width)**PHPExcel always +operates with 3) "Full width in character units"** which is in fact the +only value that is stored in any Excel file, hence the most reliable +measure. Unfortunately, **Microsoft Office Excel does not present you +with this measure**. Instead measures 1) and 2) are computed by the +application when the file is opened and these values are presented in +various dialogues and tool tips.The character width unit is the width of +a '0' (zero) glyph in the workbooks default font. Therefore column +widths measured in character units in two different workbooks can only +be compared if they have the same default workbook font.If you have some +Excel file and need to know the column widths in measure 3), you can +read the Excel file with PhpSpreadsheet and echo the retrieved values. ## Show/hide a column -To set a worksheet's column visibility, you can use the following code. The first line explicitly shows the column C, the second line hides column D. +To set a worksheet's column visibility, you can use the following code. +The first line explicitly shows the column C, the second line hides +column D. -```php +``` php $spreadsheet->getActiveSheet()->getColumnDimension('C')->setVisible(true); $spreadsheet->getActiveSheet()->getColumnDimension('D')->setVisible(false); ``` @@ -908,22 +1074,26 @@ $spreadsheet->getActiveSheet()->getColumnDimension('D')->setVisible(false); To group/outline a column, you can use the following code: -```php +``` php $spreadsheet->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1); ``` -You can also collapse the column. Note that you should also set the column invisible, otherwise the collapse will not be visible in Excel 2007. +You can also collapse the column. Note that you should also set the +column invisible, otherwise the collapse will not be visible in Excel +2007. -```php +``` php $spreadsheet->getActiveSheet()->getColumnDimension('E')->setCollapsed(true); $spreadsheet->getActiveSheet()->getColumnDimension('E')->setVisible(false); ``` -Please refer to the section "group/outline a row" for a complete example on collapsing. +Please refer to the section "group/outline a row" for a complete example +on collapsing. -You can instruct PhpSpreadsheet to add a summary to the right (default), or to the left. The following code adds the summary to the left: +You can instruct PhpSpreadsheet to add a summary to the right (default), +or to the left. The following code adds the summary to the left: -```php +``` php $spreadsheet->getActiveSheet()->setShowSummaryRight(false); ``` @@ -931,40 +1101,46 @@ $spreadsheet->getActiveSheet()->setShowSummaryRight(false); A row's height can be set using the following code: -```php +``` php $spreadsheet->getActiveSheet()->getRowDimension('10')->setRowHeight(100); ``` -Excel measures row height in points, where 1 pt is 1/72 of an inch (or about 0.35mm). The default value is 12.75 pts; and the permitted range of values is between 0 and 409 pts, where 0 pts is a hidden row. +Excel measures row height in points, where 1 pt is 1/72 of an inch (or +about 0.35mm). The default value is 12.75 pts; and the permitted range +of values is between 0 and 409 pts, where 0 pts is a hidden row. ## Show/hide a row -To set a worksheet''s row visibility, you can use the following code. The following example hides row number 10. +To set a worksheet''s row visibility, you can use the following code. +The following example hides row number 10. -```php +``` php $spreadsheet->getActiveSheet()->getRowDimension('10')->setVisible(false); ``` -Note that if you apply active filters using an AutoFilter, then this will override any rows that you hide or unhide manually within that AutoFilter range if you save the file. +Note that if you apply active filters using an AutoFilter, then this +will override any rows that you hide or unhide manually within that +AutoFilter range if you save the file. ## Group/outline a row To group/outline a row, you can use the following code: -```php +``` php $spreadsheet->getActiveSheet()->getRowDimension('5')->setOutlineLevel(1); ``` -You can also collapse the row. Note that you should also set the row invisible, otherwise the collapse will not be visible in Excel 2007. +You can also collapse the row. Note that you should also set the row +invisible, otherwise the collapse will not be visible in Excel 2007. -```php +``` php $spreadsheet->getActiveSheet()->getRowDimension('5')->setCollapsed(true); $spreadsheet->getActiveSheet()->getRowDimension('5')->setVisible(false); ``` Here's an example which collapses rows 50 to 80: -```php +``` php for ($i = 51; $i <= 80; $i++) { $spreadsheet->getActiveSheet()->setCellValue('A' . $i, "FName $i"); $spreadsheet->getActiveSheet()->setCellValue('B' . $i, "LName $i"); @@ -978,39 +1154,46 @@ for ($i = 51; $i <= 80; $i++) { $spreadsheet->getActiveSheet()->getRowDimension(81)->setCollapsed(true); ``` -You can instruct PhpSpreadsheet to add a summary below the collapsible rows (default), or above. The following code adds the summary above: +You can instruct PhpSpreadsheet to add a summary below the collapsible +rows (default), or above. The following code adds the summary above: -```php +``` php $spreadsheet->getActiveSheet()->setShowSummaryBelow(false); ``` ## Merge/unmerge cells -If you have a big piece of data you want to display in a worksheet, you can merge two or more cells together, to become one cell. This can be done using the following code: +If you have a big piece of data you want to display in a worksheet, you +can merge two or more cells together, to become one cell. This can be +done using the following code: -```php +``` php $spreadsheet->getActiveSheet()->mergeCells('A18:E22'); ``` Removing a merge can be done using the unmergeCells method: -```php +``` php $spreadsheet->getActiveSheet()->unmergeCells('A18:E22'); ``` ## Inserting rows/columns -You can insert/remove rows/columns at a specific position. The following code inserts 2 new rows, right before row 7: +You can insert/remove rows/columns at a specific position. The following +code inserts 2 new rows, right before row 7: -```php +``` php $spreadsheet->getActiveSheet()->insertNewRowBefore(7, 2); ``` ## Add a drawing to a worksheet -A drawing is always represented as a separate object, which can be added to a worksheet. Therefore, you must first instantiate a new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing, and assign its properties a meaningful value: +A drawing is always represented as a separate object, which can be added +to a worksheet. Therefore, you must first instantiate a new +\PhpOffice\PhpSpreadsheet\Worksheet\Drawing, and assign its properties a +meaningful value: -```php +``` php $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $drawing->setName('Logo'); $drawing->setDescription('Logo'); @@ -1018,15 +1201,17 @@ $drawing->setPath('./images/officelogo.jpg'); $drawing->setHeight(36); ``` -To add the above drawing to the worksheet, use the following snippet of code. PhpSpreadsheet creates the link between the drawing and the worksheet: +To add the above drawing to the worksheet, use the following snippet of +code. PhpSpreadsheet creates the link between the drawing and the +worksheet: -```php +``` php $drawing->setWorksheet($spreadsheet->getActiveSheet()); ``` You can set numerous properties on a drawing, here are some examples: -```php +``` php $drawing->setName('Paid'); $drawing->setDescription('Paid'); $drawing->setPath('./images/paid.png'); @@ -1037,9 +1222,10 @@ $drawing->getShadow()->setVisible(true); $drawing->getShadow()->setDirection(45); ``` -You can also add images created using GD functions without needing to save them to disk first as In-Memory drawings. +You can also add images created using GD functions without needing to +save them to disk first as In-Memory drawings. -```php +``` php // Use GD to create an in-memory image $gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream'); $textColor = imagecolorallocate($gdImage, 255, 255, 255); @@ -1061,11 +1247,13 @@ $drawing->setWorksheet($spreadsheet->getActiveSheet()); ## Reading Images from a worksheet -A commonly asked question is how to retrieve the images from a workbook that has been loaded, and save them as individual image files to disk. +A commonly asked question is how to retrieve the images from a workbook +that has been loaded, and save them as individual image files to disk. -The following code extracts images from the current active worksheet, and writes each as a separate file. +The following code extracts images from the current active worksheet, +and writes each as a separate file. -```php +``` php $i = 0; foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) { if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) { @@ -1103,11 +1291,14 @@ foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) { ## Add rich text to a cell -Adding rich text to a cell can be done using \PhpOffice\PhpSpreadsheet\RichText instances. Here''s an example, which creates the following rich text string: +Adding rich text to a cell can be done using +\PhpOffice\PhpSpreadsheet\RichText instances. Here''s an example, which +creates the following rich text string: - > This invoice is *__payable within thirty days after the end of the month__* unless specified otherwise on the invoice. +> This invoice is ***payable within thirty days after the end of the +> month*** unless specified otherwise on the invoice. -```php +``` php $richText = new \PhpOffice\PhpSpreadsheet\RichText(); $richText->createText('This invoice is '); $payable = $richText->createTextRun('payable within thirty days after the end of the month'); @@ -1120,9 +1311,10 @@ $spreadsheet->getActiveSheet()->getCell('A18')->setValue($richText); ## Define a named range -PhpSpreadsheet supports the definition of named ranges. These can be defined using the following code: +PhpSpreadsheet supports the definition of named ranges. These can be +defined using the following code: -```php +``` php // Add some data $spreadsheet->setActiveSheetIndex(0); $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname:'); @@ -1135,26 +1327,37 @@ $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonFN' $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonLN', $spreadsheet->getActiveSheet(), 'B2') ); ``` -Optionally, a fourth parameter can be passed defining the named range local (i.e. only usable on the current worksheet). Named ranges are global by default. +Optionally, a fourth parameter can be passed defining the named range +local (i.e. only usable on the current worksheet). Named ranges are +global by default. ## Redirect output to a client's web browser -Sometimes, one really wants to output a file to a client''s browser, especially when creating spreadsheets on-the-fly. There are some easy steps that can be followed to do this: +Sometimes, one really wants to output a file to a client''s browser, +especially when creating spreadsheets on-the-fly. There are some easy +steps that can be followed to do this: - 1. Create your PhpSpreadsheet spreadsheet - 2. Output HTTP headers for the type of document you wish to output - 3. Use the \PhpOffice\PhpSpreadsheet\Writer\* of your choice, and save to "php://output" +1. Create your PhpSpreadsheet spreadsheet +2. Output HTTP headers for the type of document you wish to output +3. Use the \PhpOffice\PhpSpreadsheet\Writer\* of your choice, and save + to "php://output" -\PhpOffice\PhpSpreadsheet\Writer\Xlsx uses temporary storage when writing to php://output. By default, temporary files are stored in the script's working directory. When there is no access, it falls back to the operating system's temporary files location. +\PhpOffice\PhpSpreadsheet\Writer\Xlsx uses temporary storage when +writing to php://output. By default, temporary files are stored in the +script's working directory. When there is no access, it falls back to +the operating system's temporary files location. -__This may not be safe for unauthorized viewing!__ -Depending on the configuration of your operating system, temporary storage can be read by anyone using the same temporary storage folder. When confidentiality of your document is needed, it is recommended not to use php://output. +**This may not be safe for unauthorized viewing!** Depending on the +configuration of your operating system, temporary storage can be read by +anyone using the same temporary storage folder. When confidentiality of +your document is needed, it is recommended not to use php://output. ### HTTP headers -Example of a script redirecting an Excel 2007 file to the client's browser: +Example of a script redirecting an Excel 2007 file to the client's +browser: -```php +``` php /* Here there will be some code where you create $spreadsheet */ // redirect output to client browser @@ -1168,7 +1371,7 @@ $writer->save('php://output'); Example of a script redirecting an Xls file to the client's browser: -```php +``` php /* Here there will be some code where you create $spreadsheet */ // redirect output to client browser @@ -1182,14 +1385,21 @@ $writer->save('php://output'); **Caution:** -Make sure not to include any echo statements or output any other contents than the Excel file. There should be no whitespace before the opening `` tag (which can also be omitted to avoid problems). Make sure that your script is saved without a BOM (Byte-order mark) because this counts as echoing output. The same things apply to all included files. -Failing to follow the above guidelines may result in corrupt Excel files arriving at the client browser, and/or that headers cannot be set by PHP (resulting in warning messages). +Make sure not to include any echo statements or output any other +contents than the Excel file. There should be no whitespace before the +opening `` +tag (which can also be omitted to avoid problems). Make sure that your +script is saved without a BOM (Byte-order mark) because this counts as +echoing output. The same things apply to all included files. Failing to +follow the above guidelines may result in corrupt Excel files arriving +at the client browser, and/or that headers cannot be set by PHP +(resulting in warning messages). ## Setting the default column width Default column width can be set using the following code: -```php +``` php $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12); ``` @@ -1197,17 +1407,20 @@ $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12); Default row height can be set using the following code: -```php +``` php $spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15); ``` ## Add a GD drawing to a worksheet -There might be a situation where you want to generate an in-memory image using GD and add it to a `Spreadsheet` without first having to save this file to a temporary location. +There might be a situation where you want to generate an in-memory image +using GD and add it to a `Spreadsheet` without first having to save this +file to a temporary location. -Here''s an example which generates an image in memory and adds it to the active worksheet: +Here''s an example which generates an image in memory and adds it to the +active worksheet: -```php +``` php // Generate an image $gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream'); $textColor = imagecolorallocate($gdImage, 255, 255, 255); @@ -1228,7 +1441,7 @@ $drawing->setWorksheet($spreadsheet->getActiveSheet()); To set a worksheet's zoom level, the following code can be used: -```php +``` php $spreadsheet->getActiveSheet()->getSheetView()->setZoomScale(75); ``` @@ -1236,9 +1449,10 @@ Note that zoom level should be in range 10 - 400. ## Sheet tab color -Sometimes you want to set a color for sheet tab. For example you can have a red sheet tab: +Sometimes you want to set a color for sheet tab. For example you can +have a red sheet tab: -```php +``` php $worksheet->getTabColor()->setRGB('FF0000'); ``` @@ -1246,36 +1460,52 @@ $worksheet->getTabColor()->setRGB('FF0000'); If you need to create more worksheets in the workbook, here is how: -```php +``` php $worksheet1 = $spreadsheet->createSheet(); $worksheet1->setTitle('Another sheet'); ``` -Think of createSheet() as the "Insert sheet" button in Excel. When you hit that button a new sheet is appended to the existing collection of worksheets in the workbook. +Think of createSheet() as the "Insert sheet" button in Excel. When you +hit that button a new sheet is appended to the existing collection of +worksheets in the workbook. ## Hidden worksheets (Sheet states) -Set a worksheet to be __hidden__ using this code: +Set a worksheet to be **hidden** using this code: -```php +``` php $spreadsheet->getActiveSheet() ->setSheetState(\PhpOffice\PhpSpreadsheet\Worksheet::SHEETSTATE_HIDDEN); ``` -Sometimes you may even want the worksheet to be __"very hidden"__. The available sheet states are : +Sometimes you may even want the worksheet to be **"very hidden"**. The +available sheet states are : - - `\PhpOffice\PhpSpreadsheet\Worksheet::SHEETSTATE_VISIBLE` - - `\PhpOffice\PhpSpreadsheet\Worksheet::SHEETSTATE_HIDDEN` - - `\PhpOffice\PhpSpreadsheet\Worksheet::SHEETSTATE_VERYHIDDEN` +- `\PhpOffice\PhpSpreadsheet\Worksheet::SHEETSTATE_VISIBLE` +- `\PhpOffice\PhpSpreadsheet\Worksheet::SHEETSTATE_HIDDEN` +- `\PhpOffice\PhpSpreadsheet\Worksheet::SHEETSTATE_VERYHIDDEN` -In Excel the sheet state "very hidden" can only be set programmatically, e.g. with Visual Basic Macro. It is not possible to make such a sheet visible via the user interface. +In Excel the sheet state "very hidden" can only be set programmatically, +e.g. with Visual Basic Macro. It is not possible to make such a sheet +visible via the user interface. ## Right-to-left worksheet -Worksheets can be set individually whether column "A" should start at left or right side. Default is left. Here is how to set columns from right-to-left. +Worksheets can be set individually whether column "A" should start at +left or right side. Default is left. Here is how to set columns from +right-to-left. -```php +``` php // right-to-left worksheet $spreadsheet->getActiveSheet()->setRightToLeft(true); ``` +[^1]: z + + ``` php + $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing(); + $drawing->setName('PhpSpreadsheet logo'); + $drawing->setPath('./images/PhpSpreadsheet_logo.png'); + $drawing->setHeight(36); + $spreadsheet->getActiveSheet()->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT); + ``` diff --git a/docs/topics/settings.md b/docs/topics/settings.md index d20a4ecc..a8f7b422 100644 --- a/docs/topics/settings.md +++ b/docs/topics/settings.md @@ -1,46 +1,78 @@ # Configuration Settings -Once you have included the PhpSpreadsheet files in your script, but before instantiating a `Spreadsheet` object or loading a workbook file, there are a number of configuration options that can be set which will affect the subsequent behaviour of the script. +Once you have included the PhpSpreadsheet files in your script, but +before instantiating a `Spreadsheet` object or loading a workbook file, +there are a number of configuration options that can be set which will +affect the subsequent behaviour of the script. ## Cell Caching -PhpSpreadsheet uses an average of about 1k/cell in your worksheets, so large workbooks can quickly use up available memory. Cell caching provides a mechanism that allows PhpSpreadsheet to maintain the cell objects in a smaller size of memory, on disk, or in APC, memcache or Wincache, rather than in PHP memory. This allows you to reduce the memory usage for large workbooks, although at a cost of speed to access cell data. +PhpSpreadsheet uses an average of about 1k/cell in your worksheets, so +large workbooks can quickly use up available memory. Cell caching +provides a mechanism that allows PhpSpreadsheet to maintain the cell +objects in a smaller size of memory, on disk, or in APC, memcache or +Wincache, rather than in PHP memory. This allows you to reduce the +memory usage for large workbooks, although at a cost of speed to access +cell data. -By default, PhpSpreadsheet still holds all cell objects in memory, but you can specify alternatives. To enable cell caching, you must call the \PhpOffice\PhpSpreadsheet\Settings::setCacheStorageMethod() method, passing in the caching method that you wish to use. +By default, PhpSpreadsheet still holds all cell objects in memory, but +you can specify alternatives. To enable cell caching, you must call the +\PhpOffice\PhpSpreadsheet\Settings::setCacheStorageMethod() method, +passing in the caching method that you wish to use. -```php +``` php $cacheMethod = \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_IN_MEMORY; \PhpOffice\PhpSpreadsheet\Settings::setCacheStorageMethod($cacheMethod); ``` -setCacheStorageMethod() will return a boolean true on success, false on failure (for example if trying to cache to APC when APC is not enabled). +setCacheStorageMethod() will return a boolean true on success, false on +failure (for example if trying to cache to APC when APC is not enabled). -A separate cache is maintained for each individual worksheet, and is automatically created when the worksheet is instantiated based on the caching method and settings that you have configured. You cannot change the configuration settings once you have started to read a workbook, or have created your first worksheet. +A separate cache is maintained for each individual worksheet, and is +automatically created when the worksheet is instantiated based on the +caching method and settings that you have configured. You cannot change +the configuration settings once you have started to read a workbook, or +have created your first worksheet. Currently, the following caching methods are available. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_IN_MEMORY +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_IN\_MEMORY -The default. If you don't initialise any caching method, then this is the method that PhpSpreadsheet will use. Cell objects are maintained in PHP memory as at present. +The default. If you don't initialise any caching method, then this is +the method that PhpSpreadsheet will use. Cell objects are maintained in +PHP memory as at present. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_IN_MEMORY_SERIALIZED +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_IN\_MEMORY\_SERIALIZED -Using this caching method, cells are held in PHP memory as an array of serialized objects, which reduces the memory footprint with minimal performance overhead. +Using this caching method, cells are held in PHP memory as an array of +serialized objects, which reduces the memory footprint with minimal +performance overhead. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_IN_MEMORY_GZIP +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_IN\_MEMORY\_GZIP -Like cache_in_memory_serialized, this method holds cells in PHP memory as an array of serialized objects, but gzipped to reduce the memory usage still further, although access to read or write a cell is slightly slower. +Like cache\_in\_memory\_serialized, this method holds cells in PHP +memory as an array of serialized objects, but gzipped to reduce the +memory usage still further, although access to read or write a cell is +slightly slower. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_IGBINARY +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_IGBINARY -Uses PHPs igbinary extension (if its available) to serialize cell objects in memory. This is normally faster and uses less memory than standard PHP serialization, but isnt available in most hosting environments. +Uses PHPs igbinary extension (if its available) to serialize cell +objects in memory. This is normally faster and uses less memory than +standard PHP serialization, but isnt available in most hosting +environments. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_DISCISAM +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_TO\_DISCISAM -When using CACHE_TO_DISCISAM all cells are held in a temporary disk file, with only an index to their location in that file maintained in PHP memory. This is slower than any of the CACHE_IN_MEMORY methods, but significantly reduces the memory footprint. By default, PhpSpreadsheet will use PHP's temp directory for the cache file, but you can specify a different directory when initialising CACHE_TO_DISCISAM. +When using CACHE\_TO\_DISCISAM all cells are held in a temporary disk +file, with only an index to their location in that file maintained in +PHP memory. This is slower than any of the CACHE\_IN\_MEMORY methods, +but significantly reduces the memory footprint. By default, +PhpSpreadsheet will use PHP's temp directory for the cache file, but you +can specify a different directory when initialising CACHE\_TO\_DISCISAM. -```php +``` php $cacheMethod = \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_DISCISAM; $cacheSettings = array( 'dir' => '/usr/local/tmp' @@ -48,13 +80,19 @@ $cacheSettings = array( \PhpOffice\PhpSpreadsheet\Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); ``` -The temporary disk file is automatically deleted when your script terminates. +The temporary disk file is automatically deleted when your script +terminates. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_PHPTEMP +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_TO\_PHPTEMP -Like CACHE_TO_DISCISAM, when using CACHE_TO_PHPTEMP all cells are held in the php://temp I/O stream, with only an index to their location maintained in PHP memory. In PHP, the php://memory wrapper stores data in the memory: php://temp behaves similarly, but uses a temporary file for storing the data when a certain memory limit is reached. The default is 1 MB, but you can change this when initialising CACHE_TO_PHPTEMP. +Like CACHE\_TO\_DISCISAM, when using CACHE\_TO\_PHPTEMP all cells are +held in the php://temp I/O stream, with only an index to their location +maintained in PHP memory. In PHP, the php://memory wrapper stores data +in the memory: php://temp behaves similarly, but uses a temporary file +for storing the data when a certain memory limit is reached. The default +is 1 MB, but you can change this when initialising CACHE\_TO\_PHPTEMP. -```php +``` php $cacheMethod = \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_PHPTEMP; $cacheSettings = array( 'memoryCacheSize' => '8MB' @@ -62,13 +100,18 @@ $cacheSettings = array( \PhpOffice\PhpSpreadsheet\Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); ``` -The php://temp file is automatically deleted when your script terminates. +The php://temp file is automatically deleted when your script +terminates. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_APC +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_TO\_APC -When using CACHE_TO_APC, cell objects are maintained in APC with only an index maintained in PHP memory to identify that the cell exists. By default, an APC cache timeout of 600 seconds is used, which should be enough for most applications: although it is possible to change this when initialising CACHE_TO_APC. +When using CACHE\_TO\_APC, cell objects are maintained in APC with only +an index maintained in PHP memory to identify that the cell exists. By +default, an APC cache timeout of 600 seconds is used, which should be +enough for most applications: although it is possible to change this +when initialising CACHE\_TO\_APC. -```php +``` php $cacheMethod = \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_APC; $cacheSettings = array( 'cacheTime' => 600 @@ -76,15 +119,22 @@ $cacheSettings = array( \PhpOffice\PhpSpreadsheet\Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); ``` -When your script terminates all entries will be cleared from APC, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism. +When your script terminates all entries will be cleared from APC, +regardless of the cacheTime value, so it cannot be used for persistent +storage using this mechanism. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_MEMCACHE +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_TO\_MEMCACHE -When using CACHE_TO_MEMCACHE, cell objects are maintained in memcache with only an index maintained in PHP memory to identify that the cell exists. +When using CACHE\_TO\_MEMCACHE, cell objects are maintained in memcache +with only an index maintained in PHP memory to identify that the cell +exists. -By default, PhpSpreadsheet looks for a memcache server on localhost at port 11211. It also sets a memcache timeout limit of 600 seconds. If you are running memcache on a different server or port, then you can change these defaults when you initialise CACHE_TO_MEMCACHE: +By default, PhpSpreadsheet looks for a memcache server on localhost at +port 11211. It also sets a memcache timeout limit of 600 seconds. If you +are running memcache on a different server or port, then you can change +these defaults when you initialise CACHE\_TO\_MEMCACHE: -```php +``` php $cacheMethod = \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_MEMCACHE; $cacheSettings = array( 'memcacheServer' => 'localhost', @@ -94,13 +144,19 @@ $cacheSettings = array( \PhpOffice\PhpSpreadsheet\Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); ``` -When your script terminates all entries will be cleared from memcache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism. +When your script terminates all entries will be cleared from memcache, +regardless of the cacheTime value, so it cannot be used for persistent +storage using this mechanism. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_WINCACHE +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_TO\_WINCACHE -When using CACHE_TO_WINCACHE, cell objects are maintained in Wincache with only an index maintained in PHP memory to identify that the cell exists. By default, a Wincache cache timeout of 600 seconds is used, which should be enough for most applications: although it is possible to change this when initialising CACHE_TO_WINCACHE. +When using CACHE\_TO\_WINCACHE, cell objects are maintained in Wincache +with only an index maintained in PHP memory to identify that the cell +exists. By default, a Wincache cache timeout of 600 seconds is used, +which should be enough for most applications: although it is possible to +change this when initialising CACHE\_TO\_WINCACHE. -```php +``` php $cacheMethod = \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_WINCACHE; $cacheSettings = array( 'cacheTime' => 600 @@ -108,22 +164,33 @@ $cacheSettings = array( \PhpOffice\PhpSpreadsheet\Settings::setCacheStorageMethod($cacheMethod, $cacheSettings); ``` -When your script terminates all entries will be cleared from Wincache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism. +When your script terminates all entries will be cleared from Wincache, +regardless of the cacheTime value, so it cannot be used for persistent +storage using this mechanism. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_SQLITE +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_TO\_SQLITE -Uses an SQLite 2 "in-memory" database for caching cell data. Unlike other caching methods, neither cells nor an index are held in PHP memory - an indexed database table makes it unnecessary to hold any index in PHP memory, which makes this the most memory-efficient of the cell caching methods. +Uses an SQLite 2 "in-memory" database for caching cell data. Unlike +other caching methods, neither cells nor an index are held in PHP memory +- an indexed database table makes it unnecessary to hold any index in +PHP memory, which makes this the most memory-efficient of the cell +caching methods. -### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_SQLITE3; - -Uses an SQLite 3 "in-memory" database for caching cell data. Unlike other caching methods, neither cells nor an index are held in PHP memory - an indexed database table makes it unnecessary to hold any index in PHP memory, which makes this the most memory-efficient of the cell caching methods. +### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE\_TO\_SQLITE3; +Uses an SQLite 3 "in-memory" database for caching cell data. Unlike +other caching methods, neither cells nor an index are held in PHP memory +- an indexed database table makes it unnecessary to hold any index in +PHP memory, which makes this the most memory-efficient of the cell +caching methods. ## Language/Locale -Some localisation elements have been included in PhpSpreadsheet. You can set a locale by changing the settings. To set the locale to Brazilian Portuguese you would use: +Some localisation elements have been included in PhpSpreadsheet. You can +set a locale by changing the settings. To set the locale to Brazilian +Portuguese you would use: -```php +``` php $locale = 'pt_br'; $validLocale = \PhpOffice\PhpSpreadsheet\Settings::setLocale($locale); if (!$validLocale) { @@ -131,7 +198,12 @@ if (!$validLocale) { } ``` -If Brazilian Portuguese language files aren't available, then Portuguese will be enabled instead: if Portuguese language files aren't available, then the setLocale() method will return an error, and American English (en_us) settings will be used throughout. - -More details of the features available once a locale has been set, including a list of the languages and locales currently supported, can be found in the section of this document entitled "Locale Settings for Formulae". +If Brazilian Portuguese language files aren't available, then Portuguese +will be enabled instead: if Portuguese language files aren't available, +then the setLocale() method will return an error, and American English +(en\_us) settings will be used throughout. +More details of the features available once a locale has been set, +including a list of the languages and locales currently supported, can +be found in the section of this document entitled "Locale Settings for +Formulae".