Reorganise documentation
We aim for long pages instead of several small one, to make `CTRL+F`ing easier and URL less prone to changes in the future. There is still way to improve it though...
|
@ -1,11 +0,0 @@
|
|||
# Calculation Engine - Formula Function Reference
|
||||
|
||||
## Frequently asked questions
|
||||
|
||||
The up-to-date F.A.Q. page for PhpSpreadsheet can be found on [http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements][1].
|
||||
|
||||
### 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.
|
||||
|
||||
[1]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements
|
|
@ -1,123 +0,0 @@
|
|||
# Calculation Engine - Formula Function Reference
|
||||
|
||||
## Function Reference
|
||||
|
||||
### 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.
|
||||
|
||||
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
|
||||
\PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType($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
|
||||
|
||||
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:
|
||||
|
||||
```php
|
||||
$returnDateType = \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType();
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
##### 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.
|
||||
|
||||
##### 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.
|
||||
|
||||
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
|
||||
\PhpOffice\PhpSpreadsheet\Shared\Date::setExcelCalendar($baseDate);
|
||||
```
|
||||
|
||||
where the following constants can be used for $baseDate
|
||||
|
||||
- \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 \PhpOffice\PhpSpreadsheet\Shared\Date::getExcelCalendar() method can be used to determine the current value of this setting:
|
||||
|
||||
```php
|
||||
$baseDate = \PhpOffice\PhpSpreadsheet\Shared\Date::getExcelCalendar();
|
||||
```
|
||||
The default is CALENDAR_WINDOWS_1900.
|
||||
|
||||
##### Functions that return a Date/Time Value
|
||||
|
||||
- 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:
|
||||
|
||||
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.
|
||||
|
||||
##### Functions that expect a Date/Time Value
|
||||
|
||||
- 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:
|
||||
|
||||
##### \PhpOffice\PhpSpreadsheet\Shared\Date::ExcelToPHP($excelDate)
|
||||
|
||||
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.
|
||||
|
||||
##### \PhpOffice\PhpSpreadsheet\Shared\Date::ExcelToPHPObject($excelDate)
|
||||
|
||||
Converts a date from an Excel date/timestamp to return a PHP DateTime object.
|
||||
|
||||
##### \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($PHPDate)
|
||||
|
||||
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.
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
# Calculation Engine - Formula Function Reference
|
||||
|
||||
## General Introduction
|
||||
|
||||
### Function that are not Supported in Xls
|
||||
|
||||
Not all functions are supported by the Excel 5 Writer. Use of these functions within your workbooks will result in an error when trying to write to Xls.
|
||||
|
||||
The following is the list of those functions that are implemented within PhpSpreadsheet, but that cannot currently be written to Excel 5.
|
||||
|
||||
#### Cube Functions
|
||||
|
||||
Excel Function | Notes
|
||||
--------------------|---------
|
||||
CUBEKPIMEMBER | Not yet Implemented
|
||||
CUBEMEMBER | Not yet Implemented
|
||||
CUBEMEMBERPROPERTY | Not yet Implemented
|
||||
CUBERANKEDMEMBER | Not yet Implemented
|
||||
CUBESET | Not yet Implemented
|
||||
CUBESETCOUNT | Not yet Implemented
|
||||
CUBEVALUE | Not yet Implemented
|
||||
|
||||
|
||||
#### Database Functions
|
||||
|
||||
Excel Function | Notes
|
||||
---------------|---------
|
||||
|
||||
|
||||
#### Date and Time Functions
|
||||
|
||||
Excel Function | Notes
|
||||
---------------|---------
|
||||
EDATE | Not a standard function within Excel 5, but an add-in from the Analysis ToolPak.
|
||||
EOMONTH | Not a standard function within Excel 5, but an add-in from the Analysis ToolPak.
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
# Calculation Engine - Formula Function Reference
|
||||
|
||||
## Function Reference
|
||||
|
||||
### Cube Functions
|
||||
|
||||
#### CUBEKPIMEMBER
|
||||
|
||||
Not yet implemented.
|
||||
|
||||
#### CUBEMEMBER
|
||||
|
||||
Not yet implemented.
|
||||
|
||||
#### CUBEMEMBERPROPERTY
|
||||
|
||||
Not yet implemented.
|
||||
|
||||
#### CUBERANKEDMEMBER
|
||||
|
||||
Not yet implemented.
|
||||
|
||||
#### CUBESET
|
||||
|
||||
Not yet implemented.
|
||||
|
||||
#### CUBESETCOUNT
|
||||
|
||||
Not yet implemented.
|
||||
|
||||
#### CUBEVALUE
|
||||
|
||||
Not yet implemented.
|
||||
|
|
@ -1,618 +0,0 @@
|
|||
# Calculation Engine - Formula Function Reference
|
||||
|
||||
## Function Reference
|
||||
|
||||
### Database Functions
|
||||
|
||||
#### DAVERAGE
|
||||
|
||||
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)
|
||||
```
|
||||
|
||||
##### 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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The average value of the matching cells.
|
||||
|
||||
This is the statistical mean.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DAVERAGE(A4:E10,"Yield",A1:B2)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
// $retVal = 12
|
||||
```
|
||||
|
||||
##### Notes
|
||||
|
||||
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.
|
||||
|
||||
##### Syntax
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The count of the matching cells.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DCOUNT(A4:E10,"Height",A1:B3)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
|
||||
// $retVal = 3
|
||||
```
|
||||
|
||||
##### 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.
|
||||
|
||||
#### 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.
|
||||
|
||||
##### Syntax
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The count of the matching cells.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DCOUNTA(A4:E10,"Yield",A1:A3)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
|
||||
// $retVal = 5
|
||||
```
|
||||
|
||||
##### 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.
|
||||
|
||||
#### DGET
|
||||
|
||||
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)
|
||||
```
|
||||
|
||||
##### 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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**mixed** The value from the selected column of the matching row.
|
||||
|
||||
#### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=GET(A4:E10,"Age",A1:F2)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
// $retVal = 14
|
||||
```
|
||||
|
||||
##### Notes
|
||||
|
||||
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.
|
||||
|
||||
##### Syntax
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The maximum value of the matching cells.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DMAX(A4:E10,"Profit",A1:B2)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
// $retVal = 105
|
||||
```
|
||||
|
||||
##### Notes
|
||||
|
||||
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.
|
||||
|
||||
##### Syntax
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The minimum value of the matching cells.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DMIN(A4:E10,"Yield",A1:A3)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
// $retVal = 6
|
||||
```
|
||||
|
||||
##### Notes
|
||||
|
||||
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.
|
||||
|
||||
##### Syntax
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The product of the matching cells.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DPRODUCT(A4:E10,"Yield",A1:B2)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
// $retVal = 140
|
||||
```
|
||||
|
||||
##### Notes
|
||||
|
||||
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.
|
||||
|
||||
##### Syntax
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The estimated standard deviation of the matching cells.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DSTDEV(A4:E10,"Yield",A1:A3)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
// $retVal = 2.97
|
||||
```
|
||||
|
||||
##### Notes
|
||||
|
||||
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.
|
||||
|
||||
##### Syntax
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The estimated standard deviation of the matching cells.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DSTDEVP(A4:E10,"Yield",A1:A3)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
// $retVal = 2.65
|
||||
```
|
||||
|
||||
##### Notes
|
||||
|
||||
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.
|
||||
|
||||
##### Syntax
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
##### Return Value
|
||||
|
||||
**float** The total value of the matching cells.
|
||||
|
||||
##### Examples
|
||||
|
||||
```php
|
||||
$database = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit' ),
|
||||
array( 'Apple', 18, 20, 14, 105.00 ),
|
||||
array( 'Pear', 12, 12, 10, 96.00 ),
|
||||
array( 'Cherry', 13, 14, 9, 105.00 ),
|
||||
array( 'Apple', 14, 15, 10, 75.00 ),
|
||||
array( 'Pear', 9, 8, 8, 76.80 ),
|
||||
array( 'Apple', 8, 9, 6, 45.00 ),
|
||||
);
|
||||
|
||||
$criteria = array(
|
||||
array( 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ),
|
||||
array( '="=Apple"', '>10', NULL, NULL, NULL, '<16' ),
|
||||
array( '="=Pear"', NULL, NULL, NULL, NULL, NULL ),
|
||||
);
|
||||
|
||||
$worksheet->fromArray( $criteria, NULL, 'A1' )
|
||||
->fromArray( $database, NULL, 'A4' );
|
||||
|
||||
$worksheet->setCellValue('A12', '=DMIN(A4:E10,"Profit",A1:A2)');
|
||||
|
||||
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
|
||||
// $retVal = 225
|
||||
```
|
||||
|
||||
##### Notes
|
||||
|
||||
There are no additional notes on this function
|
||||
|
||||
#### DVAR
|
||||
|
||||
Not yet documented.
|
||||
|
||||
#### DVARP
|
||||
|
||||
Not yet documented.
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## AutoFilters
|
||||
|
||||
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 "")
|
||||
|
||||
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)".
|
||||
|
||||
![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".
|
||||
|
||||
![01-04-autofilter.png](./images/01-04-autofilter.png "")
|
|
@ -1,24 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## Setting an AutoFilter area on a worksheet
|
||||
|
||||
To set an autoFilter on a range of cells.
|
||||
|
||||
```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.
|
||||
|
||||
If you want to set the whole worksheet as an autofilter region
|
||||
|
||||
```php
|
||||
$spreadsheet->getActiveSheet()->setAutoFilter(
|
||||
$spreadsheet->getActiveSheet()
|
||||
->calculateWorksheetDimension()
|
||||
);
|
||||
```
|
||||
|
||||
This enables filtering, but does not actually apply any filters.
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
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
|
||||
$autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter();
|
||||
$columnFilter = $autoFilter->getColumn('C');
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
- 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.
|
|
@ -1,52 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## Autofilter Expressions
|
||||
|
||||
### 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.
|
||||
|
||||
![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.
|
||||
|
||||
```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:
|
||||
|
||||
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
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
'France'
|
||||
);
|
||||
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
'Germany'
|
||||
);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
#### Matching Blanks
|
||||
|
||||
If you want to create a filter to select blank cells, you would use:
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
''
|
||||
);
|
||||
```
|
|
@ -1,48 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## Autofilter Expressions
|
||||
|
||||
### 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.
|
||||
|
||||
![04-02-dategroup-autofilter.png](./images/04-02-dategroup-autofilter.png "")
|
||||
|
||||
DateGroup filters are still applied as a Standard Filter type.
|
||||
|
||||
```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:
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
array(
|
||||
'year' => 2012,
|
||||
'month' => 1
|
||||
)
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP
|
||||
);
|
||||
```
|
||||
|
||||
The key values for the associative array are:
|
||||
|
||||
- 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.
|
||||
|
|
@ -1,84 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## Autofilter Expressions
|
||||
|
||||
### 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
|
||||
|
||||
![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 "")
|
||||
|
||||
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
|
||||
$columnFilter->setFilterType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER
|
||||
);
|
||||
```
|
||||
|
||||
And then define our rules.
|
||||
|
||||
The following shows a simple wildcard filter to show all column entries beginning with the letter 'U'.
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
'U*'
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
To create a "between" condition, we need to define two rules:
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL,
|
||||
-20
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
|
||||
);
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL,
|
||||
20
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```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:
|
||||
|
||||
Operator Constant | Value |
|
||||
------------------------------------------|----------------------|
|
||||
AUTOFILTER_COLUMN_RULE_EQUAL | 'equal' |
|
||||
AUTOFILTER_COLUMN_RULE_NOTEQUAL | 'notEqual' |
|
||||
AUTOFILTER_COLUMN_RULE_GREATERTHAN | 'greaterThan' |
|
||||
AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL | 'greaterThanOrEqual' |
|
||||
AUTOFILTER_COLUMN_RULE_LESSTHAN | 'lessThan' |
|
||||
AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL | 'lessThanOrEqual' |
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## Autofilter Expressions
|
||||
|
||||
### 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.
|
||||
|
||||
![04-04-dynamic-autofilter.png](./images/04-04-dynamic-autofilter.png "")
|
||||
|
||||
Again, we start by specifying a Filter type, this time a DYNAMICFILTER.
|
||||
|
||||
```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.
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
NULL,
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
Operator Constant | Value |
|
||||
-----------------------------------------|----------------|
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY | 'yesterday' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_TODAY | 'today' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW | 'tomorrow' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE | 'yearToDate' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR | 'thisYear' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER | 'thisQuarter' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH | 'thisMonth' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK | 'thisWeek' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR | 'lastYear' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER | 'lastQuarter' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH | 'lastMonth' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK | 'lastWeek' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR | 'nextYear' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER | 'nextQuarter' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH | 'nextMonth' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK | 'nextWeek' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 | 'M1' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_JANUARY | 'M1' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 | 'M2' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY | 'M2' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 | 'M3' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MARCH | 'M3' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 | 'M4' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_APRIL | 'M4' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 | 'M5' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MAY | 'M5' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 | 'M6' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_JUNE | 'M6' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 | 'M7' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_JULY | 'M7' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 | 'M8' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_AUGUST | 'M8' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 | 'M9' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER | 'M9' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 | 'M10' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER | 'M10' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 | 'M11' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER | 'M11' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 | 'M12' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER | 'M12' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 | 'Q1' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 | 'Q2' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 | 'Q3' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 | 'Q4' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE | 'aboveAverage' |
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE | 'belowAverage' |
|
||||
|
||||
We can only apply a single Dynamic Filter rule to a column at a time.
|
||||
|
|
@ -1,69 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## Autofilter Expressions
|
||||
|
||||
### 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:
|
||||
|
||||
![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 "")
|
||||
|
||||
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.
|
||||
|
||||
We start by specifying a Filter type, this time a DYNAMICFILTER.
|
||||
|
||||
```php
|
||||
$columnFilter->setFilterType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER
|
||||
);
|
||||
```
|
||||
|
||||
Then we create the rule:
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT,
|
||||
5,
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE,
|
||||
5,
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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 |
|
||||
---------------------------------------|-------------|
|
||||
AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE | 'byValue' |
|
||||
AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT | 'byPercent' |
|
||||
|
||||
and
|
||||
|
||||
Operator Constant | Value |
|
||||
-------------------------------------|----------|
|
||||
AUTOFILTER_COLUMN_RULE_TOPTEN_TOP | 'top' |
|
||||
AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM | 'bottom' |
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
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.
|
||||
|
||||
```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.
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
foreach ($spreadsheet->getActiveSheet()->getRowIterator() as $row) {
|
||||
if ($spreadsheet->getActiveSheet()
|
||||
->getRowDimension($row->getRowIndex())->getVisible()) {
|
||||
echo ' Row number - ' , $row->getRowIndex() , ' ';
|
||||
echo $spreadsheet->getActiveSheet()
|
||||
->getCell(
|
||||
'C'.$row->getRowIndex()
|
||||
)
|
||||
->getValue(), ' ';
|
||||
echo $spreadsheet->getActiveSheet()
|
||||
->getCell(
|
||||
'D'.$row->getRowIndex()
|
||||
)->getFormattedValue(), ' ';
|
||||
echo EOL;
|
||||
}
|
||||
}
|
||||
```
|
|
@ -1,7 +0,0 @@
|
|||
# PhpSpreadsheet AutoFilter Reference
|
||||
|
||||
|
||||
## AutoFilter Sorting
|
||||
|
||||
In MS Excel, Autofiltering also allows the rows to be sorted. This feature is ***not*** supported by PhpSpreadsheet.
|
||||
|
|
@ -1,181 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
|
||||
## Prerequisites, Installation, FAQ and Links
|
||||
|
||||
### Software requirements
|
||||
|
||||
The following software is required to develop using PhpSpreadsheet:
|
||||
|
||||
- PHP version 5.5 or newer
|
||||
- PHP extension php_zip enabled [^phpzip_footnote]
|
||||
- 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.
|
||||
|
||||
*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:
|
||||
|
||||
/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:
|
||||
|
||||
/var/www/Examples/01simple.php
|
||||
/var/www/Examples/02types.php
|
||||
...
|
||||
|
||||
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.
|
||||
|
||||
|
||||
### Useful links and tools
|
||||
|
||||
There are some links and tools which are very useful when developing using PhpSpreadsheet. Please refer to the [PHPExcel CodePlex pages][2] for an update version of the list below.
|
||||
|
||||
#### OpenXML / SpreadsheetML
|
||||
|
||||
- __File format documentation__
|
||||
[http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm][3]
|
||||
- __OpenXML Explained e-book__
|
||||
[http://openxmldeveloper.org/articles/1970.aspx][4]
|
||||
- __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][5]
|
||||
- __OpenXML Package Explorer__
|
||||
[http://www.codeplex.com/PackageExplorer/][6]
|
||||
|
||||
|
||||
### 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][7].
|
||||
|
||||
##### 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.
|
||||
|
||||
##### PHP complains about ZipArchive not being found
|
||||
|
||||
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.
|
||||
|
||||
This can be enabled by calling:
|
||||
```php
|
||||
\PhpOffice\PhpSpreadsheet\Settings::setZipClass(\PhpOffice\PhpSpreadsheet\Settings::PCLZIP);
|
||||
```
|
||||
*before* calling the save method of the Xlsx Writer.
|
||||
|
||||
You can revert to using ZipArchive by calling:
|
||||
```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)
|
||||
|
||||
##### Excel 2007 cannot open the file generated by PHPExcel_Writer_2007 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."
|
||||
|
||||
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][8] 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.
|
||||
|
||||
##### 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).
|
||||
|
||||
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][9].
|
||||
|
||||
If you've already increased memory to a maximum, or can't change your memory limit, then [this discussion][10] 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:
|
||||
```php
|
||||
$spreadsheet->getActiveSheet()->getProtection()->setSheet(true);
|
||||
```
|
||||
|
||||
##### 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.
|
||||
|
||||
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.
|
||||
|
||||
##### 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.
|
||||
|
||||
##### 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.
|
||||
|
||||
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][11]
|
||||
- A page of advice on using [PhpSpreadsheet in the Yii framework][12]
|
||||
- [The Bakery][13] has some helper classes for reading and writing with PhpSpreadsheet within CakePHP
|
||||
- Integrating [PhpSpreadsheet into Kohana 3][14] and [?????????? PHPExcel ? Kohana Framework][15]
|
||||
- Using [PhpSpreadsheet with TYPO3][16]
|
||||
|
||||
##### Joomla Autoloader interferes with PhpSpreadsheet Autoloader
|
||||
|
||||
Thanks to peterrlynch for the following advice on resolving issues between the [PhpSpreadsheet autoloader and Joomla Autoloader][17]
|
||||
|
||||
|
||||
#### Tutorials
|
||||
|
||||
- __English PHPExcel tutorial__
|
||||
[http://openxmldeveloper.org][18]
|
||||
- __French PHPExcel tutorial__
|
||||
[http://g-ernaelsten.developpez.com/tutoriels/excel2007/][19]
|
||||
- __Russian PHPExcel Blog Postings__
|
||||
[http://www.web-junior.net/sozdanie-excel-fajjlov-s-pomoshhyu-phpexcel/][20]
|
||||
- __A Japanese-language introduction to PHPExcel__
|
||||
[http://journal.mycom.co.jp/articles/2009/03/06/phpexcel/index.html][21]
|
||||
|
||||
|
||||
[2]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=Documents&referringTitle=Home
|
||||
[3]: http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm
|
||||
[4]: http://openxmldeveloper.org/articles/1970.aspx
|
||||
[5]: http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en
|
||||
[6]: http://www.codeplex.com/PackageExplorer/
|
||||
[7]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=FAQ&referringTitle=Requirements
|
||||
[8]: http://snaps.php.net/win32/php5.2-win32-latest.zip
|
||||
[9]: http://phpexcel.codeplex.com/Thread/View.aspx?ThreadId=234150
|
||||
[10]: http://phpexcel.codeplex.com/Thread/View.aspx?ThreadId=242712
|
||||
[11]: http://http:/forum.joomla.org/viewtopic.php?f=304&t=433060
|
||||
[12]: http://www.yiiframework.com/wiki/101/how-to-use-phpexcel-external-library-with-yii/
|
||||
[13]: http://bakery.cakephp.org/articles/melgior/2010/01/26/simple-excel-spreadsheet-helper
|
||||
[14]: http://www.flynsarmy.com/2010/07/phpexcel-module-for-kohana-3/
|
||||
[15]: http://szpargalki.blogspot.com/2011/02/phpexcel-kohana-framework.html
|
||||
[16]: http://typo3.org/documentation/document-library/extension-manuals/phpexcel_library/1.1.1/view/toc/0/
|
||||
[17]: http://phpexcel.codeplex.com/discussions/211925
|
||||
[18]: http://openxmldeveloper.org
|
||||
[19]: http://g-ernaelsten.developpez.com/tutoriels/excel2007/
|
||||
[20]: http://www.web-junior.net/sozdanie-excel-fajjlov-s-pomoshhyu-phpexcel/
|
||||
[21]: http://journal.mycom.co.jp/articles/2009/03/06/phpexcel/index.html
|
||||
|
||||
|
||||
[^phpzip_footnote]: __php_zip__ is only needed by __\PhpOffice\PhpSpreadsheet\Reader\Xlsx__, __\PhpOffice\PhpSpreadsheet\Writer\Xlsx__ and __\PhpOffice\PhpSpreadsheet\Reader\Ods__. In other words, if you need PhpSpreadsheet to handle .xlsx or .ods files you will need the zip extension, but otherwise not.<br />You can remove this dependency for writing Xlsx files (though not yet for reading) by using the PCLZip library that is bundled with PhpSpreadsheet. See the FAQ section of this document for details about this. PCLZip does have a dependency on PHP's zlib extension being enabled.
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
|
||||
## Architecture
|
||||
|
||||
### Schematical
|
||||
|
||||
![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.
|
||||
|
||||
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
|
||||
function myAutoload($class) {
|
||||
...
|
||||
}
|
||||
|
||||
spl_autoload_register('myAutoload');
|
||||
```
|
||||
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, ...
|
||||
|
||||
|
||||
### Readers and writers
|
||||
|
||||
On its own, PhpSpreadsheet 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.
|
||||
|
||||
![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:
|
||||
|
||||
```php
|
||||
$spreadsheet->getProperties()->setCreator("Maarten Balliauw");
|
||||
$spreadsheet->getProperties()->setLastModifiedBy("Maarten Balliauw");
|
||||
$spreadsheet->getProperties()->setTitle("Office 2007 XLSX Test Document");
|
||||
$spreadsheet->getProperties()->setSubject("Office 2007 XLSX Test Document");
|
||||
$spreadsheet->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
|
||||
$spreadsheet->getProperties()->setKeywords("office 2007 openxml php");
|
||||
$spreadsheet->getProperties()->setCategory("Test result file");
|
||||
```
|
||||
|
||||
This can be rewritten as:
|
||||
|
||||
```php
|
||||
$spreadsheet->getProperties()
|
||||
->setCreator("Maarten Balliauw")
|
||||
->setLastModifiedBy("Maarten Balliauw")
|
||||
->setTitle("Office 2007 XLSX Test Document")
|
||||
->setSubject("Office 2007 XLSX Test Document")
|
||||
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
|
||||
->setKeywords("office 2007 openxml php")
|
||||
->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.
|
|
@ -1,34 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
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.
|
||||
|
||||
#### 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 PhpSpreadsheet User Documentation - Reading Spreadsheet Files document.
|
||||
|
||||
```php
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Load $inputFileName to a Spreadsheet object **/
|
||||
$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.
|
||||
|
||||
```php
|
||||
/** Create a new Spreadsheet Object **/
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
```
|
||||
|
||||
A new workbook will always be created with a single worksheet.
|
|
@ -1,13 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
## 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.
|
||||
|
||||
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
|
||||
$spreadsheet->disconnectWorksheets();
|
||||
|
||||
unset($spreadsheet);
|
||||
```
|
|
@ -1,94 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
## Worksheets
|
||||
|
||||
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 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).
|
||||
|
||||
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
|
||||
// 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.
|
||||
|
||||
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.
|
||||
|
||||
```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).
|
||||
|
||||
```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.
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
$spreadsheet->createSheet();
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```php
|
||||
// Create a new worksheet called "My Data"
|
||||
$myWorkSheet = new \PhpOffice\PhpSpreadsheet\Worksheet($spreadsheet, 'My Data');
|
||||
|
||||
// Attach the "My Data" worksheet as the first worksheet in the Spreadsheet object
|
||||
$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.
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
$objClonedWorksheet = clone $spreadsheet->getSheetByName('Worksheet 1');
|
||||
$objClonedWorksheet->setTitle('Copy of Worksheet 1')
|
||||
$spreadsheet->addSheet($objClonedWorksheet);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```
|
||||
$objClonedWorksheet = clone $spreadsheet1->getSheetByName('Worksheet 1');
|
||||
$spreadsheet->addExternalSheet($objClonedWorksheet);
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
```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.
|
||||
|
|
@ -1,390 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
## Accessing cells
|
||||
|
||||
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.
|
||||
|
||||
```php
|
||||
// Set cell A1 with a string value
|
||||
$spreadsheet->getActiveSheet()->setCellValue('A1', 'PhpSpreadsheet');
|
||||
|
||||
// Set cell A2 with a numeric value
|
||||
$spreadsheet->getActiveSheet()->setCellValue('A2', 12345.6789);
|
||||
|
||||
// Set cell A3 with a boolean value
|
||||
$spreadsheet->getActiveSheet()->setCellValue('A3', TRUE);
|
||||
|
||||
// Set cell A4 with a formula
|
||||
$spreadsheet->getActiveSheet()->setCellValue(
|
||||
'A4',
|
||||
'=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))'
|
||||
);
|
||||
```
|
||||
|
||||
Alternatively, you can retrieve the cell object, and then call the cell’s setValue() method:
|
||||
|
||||
```php
|
||||
$spreadsheet->getActiveSheet()
|
||||
->getCell('B8')
|
||||
->setValue('Some value');
|
||||
```
|
||||
|
||||
**Excel DataTypes**
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```php
|
||||
// Get the current date/time and convert to an Excel date/time
|
||||
$dateTimeNow = time();
|
||||
$excelDateValue = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel( $dateTimeNow );
|
||||
// Set cell A6 with the Excel date/time value
|
||||
$spreadsheet->getActiveSheet()->setCellValue(
|
||||
'A6',
|
||||
$excelDateValue
|
||||
);
|
||||
// Set the number format mask so that the excel timestamp will be displayed as a human-readable date/time
|
||||
$spreadsheet->getActiveSheet()->getStyle('A6')
|
||||
->getNumberFormat()
|
||||
->setFormatCode(
|
||||
\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME
|
||||
);
|
||||
```
|
||||
|
||||
#### 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".
|
||||
|
||||
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.
|
||||
|
||||
Firstly, you can set the datatype explicitly as a string so that it is not converted to a number.
|
||||
|
||||
```php
|
||||
// Set cell A8 with a numeric value, but tell PhpSpreadsheet it should be treated as a string
|
||||
$spreadsheet->getActiveSheet()->setCellValueExplicit(
|
||||
'A8',
|
||||
"01513789642",
|
||||
\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING
|
||||
);
|
||||
```
|
||||
|
||||
Alternatively, you can use a number format mask to display the value with leading zeroes.
|
||||
|
||||
```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
|
||||
$spreadsheet->getActiveSheet()->getStyle('A9')
|
||||
->getNumberFormat()
|
||||
->setFormatCode(
|
||||
'00000000000'
|
||||
);
|
||||
```
|
||||
|
||||
With number format masking, you can even break up the digits into groups to make the value more easily readable.
|
||||
|
||||
```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
|
||||
$spreadsheet->getActiveSheet()->getStyle('A10')
|
||||
->getNumberFormat()
|
||||
->setFormatCode(
|
||||
'0000-000-0000'
|
||||
);
|
||||
```
|
||||
|
||||
![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).
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
$arrayData = array(
|
||||
array(NULL, 2010, 2011, 2012),
|
||||
array('Q1', 12, 15, 21),
|
||||
array('Q2', 56, 73, 86),
|
||||
array('Q3', 52, 61, 69),
|
||||
array('Q4', 30, 32, 0),
|
||||
);
|
||||
$spreadsheet->getActiveSheet()
|
||||
->fromArray(
|
||||
$arrayData, // The data to set
|
||||
NULL, // Array values with this value will not be set
|
||||
'C3' // Top left coordinate of the worksheet range where
|
||||
// we want to set these values (default is A1)
|
||||
);
|
||||
```
|
||||
|
||||
![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.
|
||||
|
||||
```php
|
||||
$rowArray = array('Value1', 'Value2', 'Value3', 'Value4');
|
||||
$spreadsheet->getActiveSheet()
|
||||
->fromArray(
|
||||
$rowArray, // The data to set
|
||||
NULL, // Array values with this value will not be set
|
||||
'C3' // Top left coordinate of the worksheet range where
|
||||
// we want to set these values (default is A1)
|
||||
);
|
||||
```
|
||||
|
||||
![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:
|
||||
|
||||
```php
|
||||
$rowArray = array('Value1', 'Value2', 'Value3', 'Value4');
|
||||
$columnArray = array_chunk($rowArray, 1);
|
||||
$spreadsheet->getActiveSheet()
|
||||
->fromArray(
|
||||
$columnArray, // The data to set
|
||||
NULL, // Array values with this value will not be set
|
||||
'C3' // Top left coordinate of the worksheet range where
|
||||
// we want to set these values (default is A1)
|
||||
);
|
||||
```
|
||||
|
||||
![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.
|
||||
|
||||
```php
|
||||
// Get the value fom cell A1
|
||||
$cellValue = $spreadsheet->getActiveSheet()->getCell('A1')
|
||||
->getValue();
|
||||
```
|
||||
|
||||
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 .
|
||||
|
||||
```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.
|
||||
|
||||
```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.
|
||||
|
||||
```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'.
|
||||
|
||||
### 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:
|
||||
|
||||
```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
|
||||
// Get the value fom cell A4
|
||||
$cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(0, 4)
|
||||
->getCalculatedValue();
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
$dataArray = $spreadsheet->getActiveSheet()
|
||||
->rangeToArray(
|
||||
'C3:E5', // The worksheet range that we want to retrieve
|
||||
NULL, // Value that should be returned for empty cells
|
||||
TRUE, // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell)
|
||||
TRUE, // Should values be formatted (the equivalent of getFormattedValue() for each cell)
|
||||
TRUE // Should the array be indexed by cell row and cell column
|
||||
);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
Below is an example where we read all the values in a worksheet and display them in a table.
|
||||
|
||||
```php
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
|
||||
$objReader->setReadDataOnly(TRUE);
|
||||
$spreadsheet = $objReader->load("test.xlsx");
|
||||
|
||||
$objWorksheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
echo '<table>' . PHP_EOL;
|
||||
foreach ($objWorksheet->getRowIterator() as $row) {
|
||||
echo '<tr>' . PHP_EOL;
|
||||
$cellIterator = $row->getCellIterator();
|
||||
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
|
||||
// even if a cell value is not set.
|
||||
// By default, only cells that have a value
|
||||
// set will be iterated.
|
||||
foreach ($cellIterator as $cell) {
|
||||
echo '<td>' .
|
||||
$cell->getValue() .
|
||||
'</td>' . PHP_EOL;
|
||||
}
|
||||
echo '</tr>' . PHP_EOL;
|
||||
}
|
||||
echo '</table>' . 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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```php
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
|
||||
$objReader->setReadDataOnly(TRUE);
|
||||
$spreadsheet = $objReader->load("test.xlsx");
|
||||
|
||||
$objWorksheet = $spreadsheet->getActiveSheet();
|
||||
// Get the highest row and column numbers referenced in the worksheet
|
||||
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
|
||||
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
|
||||
$highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell::columnIndexFromString($highestColumn); // e.g. 5
|
||||
|
||||
echo '<table>' . "\n";
|
||||
for ($row = 1; $row <= $highestRow; ++$row) {
|
||||
echo '<tr>' . PHP_EOL;
|
||||
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
|
||||
echo '<td>' .
|
||||
$objWorksheet->getCellByColumnAndRow($col, $row)
|
||||
->getValue() .
|
||||
'</td>' . PHP_EOL;
|
||||
}
|
||||
echo '</tr>' . PHP_EOL;
|
||||
}
|
||||
echo '</table>' . PHP_EOL;
|
||||
```
|
||||
|
||||
Alternatively, you can take advantage of PHP's "Perl-style" character incrementors to loop through the cells by coordinate:
|
||||
|
||||
```php
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
|
||||
$objReader->setReadDataOnly(TRUE);
|
||||
$spreadsheet = $objReader->load("test.xlsx");
|
||||
|
||||
$objWorksheet = $spreadsheet->getActiveSheet();
|
||||
// Get the highest row number and column letter referenced in the worksheet
|
||||
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
|
||||
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
|
||||
// Increment the highest column letter
|
||||
$highestColumn++;
|
||||
|
||||
echo '<table>' . "\n";
|
||||
for ($row = 1; $row <= $highestRow; ++$row) {
|
||||
echo '<tr>' . PHP_EOL;
|
||||
for ($col = 'A'; $col != $highestColumn; ++$col) {
|
||||
echo '<td>' .
|
||||
$objWorksheet->getCell($col . $row)
|
||||
->getValue() .
|
||||
'</td>' . PHP_EOL;
|
||||
}
|
||||
echo '</tr>' . PHP_EOL;
|
||||
}
|
||||
echo '</table>' . 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.
|
||||
|
||||
### 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).
|
||||
|
||||
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
|
||||
/** PhpSpreadsheet */
|
||||
require_once 'src/Boostrap.php';
|
||||
|
||||
// Set value binder
|
||||
\PhpOffice\PhpSpreadsheet\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
|
||||
|
||||
// Create new Spreadsheet object
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
|
||||
// ...
|
||||
// Add some data, resembling some different data types
|
||||
$spreadsheet->getActiveSheet()->setCellValue('A4', 'Percentage value:');
|
||||
// Converts the string value to 0.1 and sets percentage cell style
|
||||
$spreadsheet->getActiveSheet()->setCellValue('B4', '10%');
|
||||
|
||||
$spreadsheet->getActiveSheet()->setCellValue('A5', 'Date/time value:');
|
||||
// Converts the string value to an Excel datestamp and sets the date format cell style
|
||||
$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.
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
## Using the PhpSpreadsheet calculation engine
|
||||
|
||||
### 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.
|
||||
|
||||
To calculate a formula, you can call the cell containing the formula’s method getCalculatedValue(), for example:
|
||||
|
||||
```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 "")
|
||||
|
||||
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-formula-in-cell-1.png](./images/09-formula-in-cell-1.png "")
|
||||
|
||||
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 "")
|
||||
|
||||
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.
|
||||
|
||||
#### 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.
|
||||
|
||||
Reference for operator precedence in Excel: [http://support.microsoft.com/kb/25189][18]
|
||||
|
||||
Reference for operator precedence in PHP: [http://www.php.net/operators][19]
|
||||
|
||||
#### 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.
|
||||
|
||||
Reference for this behaviour in PHP: [http://be.php.net/manual/en/language.types.string.php#language.types.string.conversion][20]
|
||||
|
||||
[18]: http://support.microsoft.com/kb/25189
|
||||
[19]: http://www.php.net/operators
|
||||
[20]: http://be.php.net/manual/en/language.types.string.php#language.types.string.conversion
|
|
@ -1,714 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
## 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 PHPExcel_Writer_IReader and \PhpOffice\PhpSpreadsheet\Writer\IWriter.
|
||||
|
||||
### \PhpOffice\PhpSpreadsheet\IOFactory
|
||||
|
||||
The PhpSpreadsheet API offers multiple methods to create a PHPExcel_Writer_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.
|
||||
|
||||
#### 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.
|
||||
|
||||
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:
|
||||
|
||||
```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.
|
||||
|
||||
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
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx");
|
||||
$objReader->setReadDataOnly(true);
|
||||
$objReader->load("05featuredemo.xlsx");
|
||||
```
|
||||
|
||||
You can create a \PhpOffice\PhpSpreadsheet\Reader\IReader instance using \PhpOffice\PhpSpreadsheet\IOFactory in explicit mode using the following code sample:
|
||||
|
||||
```php
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
|
||||
$spreadsheet = $objReader->load("05featuredemo.xlsx");
|
||||
```
|
||||
|
||||
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 PHPExcel_Writer_Iwriter instance using \PhpOffice\PhpSpreadsheet\IOFactory:
|
||||
|
||||
```php
|
||||
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
|
||||
$objWriter->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.
|
||||
|
||||
#### \PhpOffice\PhpSpreadsheet\Reader\Xlsx
|
||||
|
||||
##### Reading a spreadsheet
|
||||
|
||||
You can read an .xlsx file using the following code:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
|
||||
$objReader->setReadDataOnly(true);
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
|
||||
$objReader->setLoadSheetsOnly( array("Sheet 1", "My special sheet") );
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
|
||||
|
||||
```php
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Read title row and rows 20 - 30
|
||||
if ($row == 1 || ($row >= 20 && $row <= 30)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
|
||||
$objReader->setReadFilter( new MyReadFilter() );
|
||||
$spreadsheet = $objReader->load("06largescale.xlsx");
|
||||
```
|
||||
|
||||
#### \PhpOffice\PhpSpreadsheet\Writer\Xlsx
|
||||
|
||||
##### Writing a spreadsheet
|
||||
|
||||
You can write an .xlsx file using the following code:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
|
||||
$objWriter->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:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
|
||||
$objWriter->setPreCalculateFormulas(false);
|
||||
$objWriter->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:
|
||||
|
||||
```
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
|
||||
$objWriter->setOffice2003Compatibility(true);
|
||||
$objWriter->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.
|
||||
|
||||
### 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][21], 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.
|
||||
|
||||
__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
|
||||
|
||||
##### Reading a spreadsheet
|
||||
|
||||
You can read an .xls file using the following code:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
|
||||
$objReader->setReadDataOnly(true);
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
|
||||
$objReader->setLoadSheetsOnly( array("Sheet 1", "My special sheet") );
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:
|
||||
|
||||
```php
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Read title row and rows 20 - 30
|
||||
if ($row == 1 || ($row >= 20 && $row <= 30)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
|
||||
$objReader->setReadFilter( new MyReadFilter() );
|
||||
$spreadsheet = $objReader->load("06largescale.xls");
|
||||
```
|
||||
|
||||
#### \PhpOffice\PhpSpreadsheet\Writer\Xls
|
||||
|
||||
##### Writing a spreadsheet
|
||||
|
||||
You can write an .xls file using the following code:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xls($spreadsheet);
|
||||
$objWriter->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 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
|
||||
|
||||
##### Reading a spreadsheet
|
||||
|
||||
You can read an Excel 2003 .xml file using the following code:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Excel2003XML();
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:
|
||||
|
||||
```php
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Read title row and rows 20 - 30
|
||||
if ($row == 1 || ($row >= 20 && $row <= 30)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Excel2003XML();
|
||||
$objReader->setReadFilter( new MyReadFilter() );
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
__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
|
||||
|
||||
##### Reading a spreadsheet
|
||||
|
||||
You can read an .slk file using the following code:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\SYLK();
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
The following code will only read row 1 and rows 20 to 30 of any sheet in the SYLK file:
|
||||
|
||||
```php
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Read title row and rows 20 - 30
|
||||
if ($row == 1 || ($row >= 20 && $row <= 30)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\SYLK();
|
||||
$objReader->setReadFilter( new MyReadFilter() );
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
#### \PhpOffice\PhpSpreadsheet\Reader\Ods
|
||||
|
||||
##### Reading a spreadsheet
|
||||
|
||||
You can read an .ods file using the following code:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Ods();
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
The following code will only read row 1 and rows 20 to 30 of any sheet in the Calc file:
|
||||
|
||||
```php
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Read title row and rows 20 - 30
|
||||
if ($row == 1 || ($row >= 20 && $row <= 30)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$objReader = new PHPExcel_Reader_OOcalc();
|
||||
$objReader->setReadFilter( new MyReadFilter() );
|
||||
$spreadsheet = $objReader->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 limitations__
|
||||
Please note that CSV file format has some limits regarding to styling cells, number formatting, ...
|
||||
|
||||
#### \PhpOffice\PhpSpreadsheet\Reader\CSV
|
||||
|
||||
##### Reading a CSV file
|
||||
|
||||
You can read a .csv file using the following code:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\CSV();
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
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
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\CSV();
|
||||
$objReader->setInputEncoding('CP1252');
|
||||
$objReader->setDelimiter(';');
|
||||
$objReader->setEnclosure('');
|
||||
$objReader->setLineEnding("\r\n");
|
||||
$objReader->setSheetIndex(0);
|
||||
|
||||
$spreadsheet = $objReader->load("sample.csv");
|
||||
```
|
||||
|
||||
##### Read a specific worksheet
|
||||
|
||||
CSV files can only contain one worksheet. Therefore, you can specify which sheet to read from CSV:
|
||||
|
||||
```php
|
||||
$objReader->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:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\CSV();
|
||||
$objReader->setDelimiter(';');
|
||||
$objReader->setEnclosure('');
|
||||
$objReader->setLineEnding("\r\n");
|
||||
$objReader->setSheetIndex(5);
|
||||
|
||||
$objReader->loadIntoExisting("05featuredemo.csv", $spreadsheet);
|
||||
```
|
||||
|
||||
#### \PhpOffice\PhpSpreadsheet\Writer\CSV
|
||||
|
||||
##### Writing a CSV file
|
||||
|
||||
You can write a .csv file using the following code:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\CSV($spreadsheet);
|
||||
$objWriter->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:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\CSV($spreadsheet);
|
||||
$objWriter->setDelimiter(';');
|
||||
$objWriter->setEnclosure('');
|
||||
$objWriter->setLineEnding("\r\n");
|
||||
$objWriter->setSheetIndex(0);
|
||||
|
||||
$objWriter->save("05featuredemo.csv");
|
||||
```
|
||||
|
||||
##### Write a specific worksheet
|
||||
|
||||
CSV files can only contain one worksheet. Therefore, you can specify which sheet to write to CSV:
|
||||
|
||||
```php
|
||||
$objWriter->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:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\CSV($spreadsheet);
|
||||
$objWriter->setPreCalculateFormulas(false);
|
||||
$objWriter->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:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\CSV($spreadsheet);
|
||||
$objWriter->setUseBOM(true);
|
||||
$objWriter->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.
|
||||
|
||||
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
|
||||
\PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator('.');
|
||||
\PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator(',');
|
||||
```
|
||||
|
||||
German users will want to use the opposite values.
|
||||
|
||||
```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.
|
||||
|
||||
### 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.
|
||||
|
||||
__HTML limitations__
|
||||
Please note that HTML file format has some limits regarding to styling cells, number formatting, ...
|
||||
|
||||
#### \PhpOffice\PhpSpreadsheet\Reader\HTML
|
||||
|
||||
##### Reading a spreadsheet
|
||||
|
||||
You can read an .html or .htm file using the following code:
|
||||
|
||||
```php
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\HTML();
|
||||
|
||||
$spreadsheet = $objReader->load("05featuredemo.html");
|
||||
```
|
||||
|
||||
__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.
|
||||
|
||||
##### Writing a spreadsheet
|
||||
|
||||
You can write a .htm file using the following code:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\HTML($spreadsheet);
|
||||
|
||||
$objWriter->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:
|
||||
|
||||
```php
|
||||
$objWriter->writeAllSheets();
|
||||
```
|
||||
|
||||
##### Write a specific worksheet
|
||||
|
||||
HTML files can contain one or more worksheets. Therefore, you can specify which sheet to write to HTML:
|
||||
|
||||
```php
|
||||
$objWriter->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
|
||||
<img style="position: relative; left: 0px; top: 0px; width: 140px; height: 78px;" src="http://www.domain.com/*images/logo.jpg" border="0">
|
||||
```
|
||||
|
||||
instead of
|
||||
|
||||
```html
|
||||
<img style="position: relative; left: 0px; top: 0px; width: 140px; height: 78px;" src="./images/logo.jpg" border="0">.
|
||||
```
|
||||
|
||||
You can use the following code to achieve this result:
|
||||
|
||||
```php
|
||||
$objWriter->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:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\HTML($spreadsheet);
|
||||
$objWriter->setPreCalculateFormulas(false);
|
||||
|
||||
$objWriter->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.
|
||||
|
||||
Supported methods:
|
||||
|
||||
- generateHTMLHeader()
|
||||
- generateStyles()
|
||||
- generateSheetData()
|
||||
- generateHTMLFooter()
|
||||
|
||||
Here's an example which retrieves all parts independently and merges them into a resulting HTML page:
|
||||
|
||||
```php
|
||||
<?php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\HTML($spreadsheet);
|
||||
echo $objWriter->generateHTMLHeader();
|
||||
?>
|
||||
|
||||
<style>
|
||||
<!--
|
||||
html {
|
||||
font-family: Times New Roman;
|
||||
font-size: 9pt;
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
<?php
|
||||
echo $objWriter->generateStyles(false); // do not write <style> and </style>
|
||||
?>
|
||||
|
||||
-->
|
||||
</style>
|
||||
|
||||
<?php
|
||||
echo $objWriter->generateSheetData();
|
||||
echo $objWriter->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:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\HTML($spreadsheet);
|
||||
$objWriter->setUseBOM(true);
|
||||
|
||||
$objWriter->save("05featuredemo.htm");
|
||||
```
|
||||
|
||||
##### Decimal and thousands separators
|
||||
|
||||
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.
|
||||
|
||||
__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.
|
||||
|
||||
Currently, the following libraries are supported:
|
||||
|
||||
Library | Version used for testing | Downloadable from | PhpSpreadsheet Internal Constant
|
||||
--------|--------------------------|----------------------------------|----------------------------
|
||||
tcPDF | 5.9 | http://www.tcpdf.org/ | PDF_RENDERER_TCPDF
|
||||
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.
|
||||
|
||||
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
|
||||
$rendererName = \PhpOffice\PhpSpreadsheet\Settings::PDF_RENDERER_MPDF;
|
||||
$rendererLibrary = 'mPDF5.4';
|
||||
$rendererLibraryPath = dirname(__FILE__).'/../../../libraries/PDF/' . $rendererLibrary;
|
||||
|
||||
if (!\PhpOffice\PhpSpreadsheet\Settings::setPdfRenderer(
|
||||
$rendererName,
|
||||
$rendererLibraryPath
|
||||
)) {
|
||||
die(
|
||||
'Please set the $rendererName and $rendererLibraryPath values' .
|
||||
PHP_EOL .
|
||||
' as appropriate for your directory structure'
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
##### 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:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\PDF($spreadsheet);
|
||||
$objWriter->save("05featuredemo.pdf");
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```php
|
||||
$objWriter->writeAllSheets();
|
||||
```
|
||||
|
||||
##### Write a specific worksheet
|
||||
|
||||
PDF files can contain one or more worksheets. Therefore, you can specify which sheet to write to PDF:
|
||||
|
||||
```php
|
||||
$objWriter->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:
|
||||
|
||||
```php
|
||||
$objWriter = new \PhpOffice\PhpSpreadsheet\Writer\PDF($spreadsheet);
|
||||
$objWriter->setPreCalculateFormulas(false);
|
||||
|
||||
$objWriter->save("05featuredemo.pdf");
|
||||
```
|
||||
|
||||
##### Decimal and thousands separators
|
||||
|
||||
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.
|
||||
|
||||
Here is an example how to open a template file, fill in a couple of fields and save it again:
|
||||
|
||||
```php
|
||||
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx');
|
||||
|
||||
$objWorksheet = $spreadsheet->getActiveSheet();
|
||||
|
||||
$objWorksheet->getCell('A1')->setValue('John');
|
||||
$objWorksheet->getCell('A2')->setValue('Smith');
|
||||
|
||||
$objWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
|
||||
$objWriter->save('write.xls');
|
||||
```
|
||||
|
||||
Notice that it is ok to load an xlsx file and generate an xls file.
|
||||
|
||||
[21]: http://pear.php.net/package/Spreadsheet_Excel_Writer
|
||||
[22]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=Credits&referringTitle=Home
|
|
@ -1,100 +0,0 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
## Credits
|
||||
|
||||
Please refer to the internet page [http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=Credits&referringTitle=Home][22] for up-to-date credits.
|
||||
|
||||
## 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.
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style__
|
||||
|
||||
Array key | Maps to property
|
||||
-------------|-------------------
|
||||
fill | getFill()
|
||||
font | getFont()
|
||||
borders | getBorders()
|
||||
alignment | getAlignment()
|
||||
numberformat | getNumberFormat()
|
||||
protection | getProtection()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Fill__
|
||||
|
||||
Array key | Maps to property
|
||||
-----------|-------------------
|
||||
type | setFillType()
|
||||
rotation | setRotation()
|
||||
startcolor | getStartColor()
|
||||
endcolor | getEndColor()
|
||||
color | getStartColor()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Font__
|
||||
|
||||
Array key | Maps to property
|
||||
------------|-------------------
|
||||
name | setName()
|
||||
bold | setBold()
|
||||
italic | setItalic()
|
||||
underline | setUnderline()
|
||||
strike | setStrikethrough()
|
||||
color | getColor()
|
||||
size | setSize()
|
||||
superScript | setSuperScript()
|
||||
subScript | setSubScript()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Borders__
|
||||
|
||||
Array key | Maps to property
|
||||
------------------|-------------------
|
||||
allborders | getLeft(); getRight(); getTop(); getBottom()
|
||||
left | getLeft()
|
||||
right | getRight()
|
||||
top | getTop()
|
||||
bottom | getBottom()
|
||||
diagonal | getDiagonal()
|
||||
vertical | getVertical()
|
||||
horizontal | getHorizontal()
|
||||
diagonaldirection | setDiagonalDirection()
|
||||
outline | setOutline()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Border__
|
||||
|
||||
Array key | Maps to property
|
||||
----------|-------------------
|
||||
style | setBorderStyle()
|
||||
color | getColor()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Alignment__
|
||||
|
||||
Array key | Maps to property
|
||||
------------|-------------------
|
||||
horizontal | setHorizontal()
|
||||
vertical | setVertical()
|
||||
rotation | setTextRotation()
|
||||
wrap | setWrapText()
|
||||
shrinkToFit | setShrinkToFit()
|
||||
indent | setIndent()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\NumberFormat__
|
||||
|
||||
Array key | Maps to property
|
||||
----------|-------------------
|
||||
code | setFormatCode()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Protection__
|
||||
|
||||
Array key | Maps to property
|
||||
----------|-------------------
|
||||
locked | setLocked()
|
||||
hidden | setHidden()
|
||||
|
||||
|
||||
[22]: http://www.codeplex.com/PHPExcel/Wiki/View.aspx?title=Credits&referringTitle=Home
|
|
@ -1,13 +0,0 @@
|
|||
# PhpSpreadsheet User Documentation – Reading Spreadsheet 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:
|
||||
|
||||
- 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.
|
|
@ -1,21 +0,0 @@
|
|||
# PhpSpreadsheet User Documentation – Reading Spreadsheet Files
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
```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.
|
||||
|
||||
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.
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
# PhpSpreadsheet User Documentation – Reading Spreadsheet Files
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
```php
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Xls Reader **/
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\Excel2003XML();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\Ods();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\SYLK();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\Gnumeric();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\CSV();
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
// $inputFileType = 'Xlsx';
|
||||
// $inputFileType = 'Excel2003XML';
|
||||
// $inputFileType = 'Ods';
|
||||
// $inputFileType = 'SYLK';
|
||||
// $inputFileType = 'Gnumeric';
|
||||
// $inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Identify the type of $inputFileName **/
|
||||
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName);
|
||||
/** Create a new Reader of the type that has been identified **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
```
|
||||
> See Examples/Reader/exampleReader04.php for a working example of this code.
|
||||
|
|
@ -1,392 +0,0 @@
|
|||
# PhpSpreadsheet User Documentation – Reading Spreadsheet Files
|
||||
|
||||
## 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.
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader that we only want to load cell data **/
|
||||
$objReader->setReadDataOnly(true);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
To read a single sheet, you can pass that sheet name as a parameter to the setLoadSheetsOnly() method.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetname = 'Data Sheet #2';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader of which WorkSheets we want to load **/
|
||||
$objReader->setLoadSheetsOnly($sheetname);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetnames = array('Data Sheet #1','Data Sheet #3');
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader of which WorkSheets we want to load **/
|
||||
$objReader->setLoadSheetsOnly($sheetnames);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader to load all Worksheets **/
|
||||
$objReader->setLoadAllSheets();
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
```
|
||||
> See Examples/Reader/exampleReader06.php for a working example of this code.
|
||||
|
||||
Reading Only Named WorkSheets from a 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 |
|
||||
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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetname = 'Data Sheet #3';
|
||||
|
||||
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Read rows 1 to 7 and columns A to E only
|
||||
if ($row >= 1 && $row <= 7) {
|
||||
if (in_array($column,range('A','E'))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create an Instance of our Read Filter **/
|
||||
$filterSubset = new MyReadFilter();
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
$objReader->setReadFilter($filterSubset);
|
||||
/** Load only the rows and columns that match our filter to Spreadsheet **/
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
```php
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
private $_startRow = 0;
|
||||
private $_endRow = 0;
|
||||
private $_columns = array();
|
||||
|
||||
/** Get the list of rows and columns to read */
|
||||
public function __construct($startRow, $endRow, $columns) {
|
||||
$this->_startRow = $startRow;
|
||||
$this->_endRow = $endRow;
|
||||
$this->_columns = $columns;
|
||||
}
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Only read the rows and columns that were configured
|
||||
if ($row >= $this->_startRow && $row <= $this->_endRow) {
|
||||
if (in_array($column,$this->_columns)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example2.xls';
|
||||
|
||||
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class chunkReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
private $_startRow = 0;
|
||||
private $_endRow = 0;
|
||||
|
||||
/** Set the list of rows that we want to read */
|
||||
public function setRows($startRow, $chunkSize) {
|
||||
$this->_startRow = $startRow;
|
||||
$this->_endRow = $startRow + $chunkSize;
|
||||
}
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Only read the heading row, and the configured rows
|
||||
if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Define how many rows we want to read for each "chunk" **/
|
||||
$chunkSize = 2048;
|
||||
/** Create a new Instance of our Read Filter **/
|
||||
$chunkFilter = new chunkReadFilter();
|
||||
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
$objReader->setReadFilter($chunkFilter);
|
||||
|
||||
/** Loop to read our worksheet in "chunk size" blocks **/
|
||||
for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) {
|
||||
/** Tell the Read Filter which rows we want this iteration **/
|
||||
$chunkFilter->setRows($startRow,$chunkSize);
|
||||
/** Load only the rows that match our filter **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
// Do some processing here
|
||||
}
|
||||
```
|
||||
> 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
|
||||
|
||||
### 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 $objReader, then use the loadIntoExisting() method rather than the load() method to actually read the file into that worksheet.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileNames = array('./sampleData/example1.csv',
|
||||
'./sampleData/example2.csv'
|
||||
'./sampleData/example3.csv'
|
||||
);
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Extract the first named file from the array list **/
|
||||
$inputFileName = array_shift($inputFileNames);
|
||||
/** Load the initial file to the first worksheet in a `Spreadsheet` Object **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
/** Set the worksheet title (to the filename that we've loaded) **/
|
||||
$spreadsheet->getActiveSheet()
|
||||
->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
|
||||
|
||||
|
||||
/** Loop through all the remaining files in the list **/
|
||||
foreach($inputFileNames as $sheet => $inputFileName) {
|
||||
/** Increment the worksheet index pointer for the Reader **/
|
||||
$objReader->setSheetIndex($sheet+1);
|
||||
/** Load the current file into a new worksheet in Spreadsheet **/
|
||||
$objReader->loadIntoExisting($inputFileName,$spreadsheet);
|
||||
/** Set the worksheet title (to the filename that we've loaded) **/
|
||||
$spreadsheet->getActiveSheet()
|
||||
->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.
|
||||
|
||||
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 |
|
||||
CSV | YES | HTML | NO
|
||||
|
||||
### 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 $objReader, we can split the CSV file across several individual worksheets.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example2.csv';
|
||||
|
||||
|
||||
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Define how many rows we want to read for each "chunk" **/
|
||||
$chunkSize = 65530;
|
||||
/** Create a new Instance of our Read Filter **/
|
||||
$chunkFilter = new chunkReadFilter();
|
||||
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
/** and that we want to store it in contiguous rows/columns **/
|
||||
|
||||
$objReader->setReadFilter($chunkFilter)
|
||||
->setContiguous(true);
|
||||
|
||||
/** Instantiate a new Spreadsheet object manually **/
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
|
||||
/** Set a sheet index **/
|
||||
$sheet = 0;
|
||||
/** Loop to read our worksheet in "chunk size" blocks **/
|
||||
/** $startRow is set to 2 initially because we always read the headings in row #1 **/
|
||||
for ($startRow = 2; $startRow <= 1000000; $startRow += $chunkSize) {
|
||||
/** Tell the Read Filter which rows we want to read this loop **/
|
||||
$chunkFilter->setRows($startRow,$chunkSize);
|
||||
|
||||
/** Increment the worksheet index pointer for the Reader **/
|
||||
$objReader->setSheetIndex($sheet);
|
||||
/** Load only the rows that match our filter into a new worksheet **/
|
||||
$objReader->loadIntoExisting($inputFileName,$spreadsheet);
|
||||
/** Set the worksheet title for the sheet that we've justloaded) **/
|
||||
/** and increment the sheet index as well **/
|
||||
$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.
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example1.tsv';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/ $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Set the delimiter to a TAB character **/
|
||||
$objReader->setDelimiter("\t");
|
||||
// $objReader->setDelimiter('|');
|
||||
|
||||
/** Load the file to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```php
|
||||
/** Tell PhpSpreadsheet that we want to use the Advanced Value Binder **/
|
||||
\PhpOffice\PhpSpreadsheet\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
|
||||
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example1.tsv';
|
||||
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
$objReader->setDelimiter("\t");
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
```
|
||||
> 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 |
|
||||
CSV | YES | HTML | YES
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
# PhpSpreadsheet User Documentation – Reading Spreadsheet Files
|
||||
|
||||
## 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.
|
||||
|
||||
The PhpSpreadsheet Readers throw a \PhpOffice\PhpSpreadsheet\Reader\Exception.
|
||||
|
||||
```php
|
||||
$inputFileName = './sampleData/example-1.xls';
|
||||
|
||||
try {
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
|
||||
} catch(\PhpOffice\PhpSpreadsheet\Reader\Exception $e) {
|
||||
die('Error loading file: '.$e->getMessage());
|
||||
}
|
||||
```
|
||||
> See Examples/Reader/exampleReader16.php for a working example of this code.
|
||||
|
|
@ -1,47 +0,0 @@
|
|||
# PhpSpreadsheet User Documentation – Reading Spreadsheet Files
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
### listWorksheetNames
|
||||
|
||||
The `listWorksheetNames()` method returns a simple array listing each worksheet name within the workbook:
|
||||
|
||||
```php
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
$worksheetNames = $objReader->listWorksheetNames($inputFileName);
|
||||
|
||||
echo '<h3>Worksheet Names</h3>';
|
||||
echo '<ol>';
|
||||
foreach ($worksheetNames as $worksheetName) {
|
||||
echo '<li>', $worksheetName, '</li>';
|
||||
}
|
||||
echo '</ol>';
|
||||
```
|
||||
> 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:
|
||||
|
||||
```php
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
$worksheetData = $objReader->listWorksheetInfo($inputFileName);
|
||||
|
||||
echo '<h3>Worksheet Information</h3>';
|
||||
echo '<ol>';
|
||||
foreach ($worksheetData as $worksheet) {
|
||||
echo '<li>', $worksheet['worksheetName'], '<br />';
|
||||
echo 'Rows: ', $worksheet['totalRows'],
|
||||
' Columns: ', $worksheet['totalColumns'], '<br />';
|
||||
echo 'Cell Range: A1:',
|
||||
$worksheet['lastColumnLetter'], $worksheet['totalRows'];
|
||||
echo '</li>';
|
||||
}
|
||||
echo '</ol>';
|
||||
```
|
||||
> See Examples/Reader/exampleReader19.php for a working example of this code.
|
|
@ -0,0 +1,94 @@
|
|||
# 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).
|
||||
|
||||
## 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.
|
||||
|
||||
## PHP complains about ZipArchive not being found
|
||||
|
||||
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.
|
||||
|
||||
This can be enabled by calling:
|
||||
|
||||
```php
|
||||
\PhpOffice\PhpSpreadsheet\Settings::setZipClass(\PhpOffice\PhpSpreadsheet\Settings::PCLZIP);
|
||||
```
|
||||
|
||||
*before* calling the save method of the Xlsx Writer.
|
||||
|
||||
You can revert to using ZipArchive by calling:
|
||||
|
||||
```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)
|
||||
|
||||
## 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."
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## 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).
|
||||
|
||||
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.
|
||||
|
||||
## 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:
|
||||
|
||||
```php
|
||||
$spreadsheet->getActiveSheet()->getProtection()->setSheet(true);
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
## 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.
|
||||
|
||||
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/)
|
||||
|
||||
## 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)
|
||||
|
||||
|
||||
### 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)
|
||||
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 9.4 KiB |
Before Width: | Height: | Size: 7.0 KiB After Width: | Height: | Size: 7.0 KiB |
Before Width: | Height: | Size: 7.8 KiB After Width: | Height: | Size: 7.8 KiB |
1367
docs/index.md
|
@ -0,0 +1,433 @@
|
|||
# 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.
|
||||
|
||||
![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.
|
||||
|
||||
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 "")
|
||||
|
||||
|
||||
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 "")
|
||||
|
||||
|
||||
## Setting an AutoFilter area on a worksheet
|
||||
|
||||
To set an autoFilter on a range of cells.
|
||||
|
||||
```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.
|
||||
|
||||
If you want to set the whole worksheet as an autofilter region
|
||||
|
||||
```php
|
||||
$spreadsheet->getActiveSheet()->setAutoFilter(
|
||||
$spreadsheet->getActiveSheet()
|
||||
->calculateWorksheetDimension()
|
||||
);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
$autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter();
|
||||
$columnFilter = $autoFilter->getColumn('C');
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
- 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.
|
||||
|
||||
|
||||
### 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.
|
||||
|
||||
![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.
|
||||
|
||||
```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:
|
||||
|
||||
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
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
'France'
|
||||
);
|
||||
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
'Germany'
|
||||
);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
#### Matching Blanks
|
||||
|
||||
If you want to create a filter to select blank cells, you would use:
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
''
|
||||
);
|
||||
```
|
||||
|
||||
### 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.
|
||||
|
||||
![04-02-dategroup-autofilter.png](./images/04-02-dategroup-autofilter.png "")
|
||||
|
||||
DateGroup filters are still applied as a Standard Filter type.
|
||||
|
||||
```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:
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
array(
|
||||
'year' => 2012,
|
||||
'month' => 1
|
||||
)
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DATEGROUP
|
||||
);
|
||||
```
|
||||
|
||||
The key values for the associative array are:
|
||||
|
||||
- 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.
|
||||
|
||||
|
||||
### 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
|
||||
|
||||
![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 "")
|
||||
|
||||
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
|
||||
$columnFilter->setFilterType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER
|
||||
);
|
||||
```
|
||||
|
||||
And then define our rules.
|
||||
|
||||
The following shows a simple wildcard filter to show all column entries beginning with the letter 'U'.
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
'U*'
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
To create a "between" condition, we need to define two rules:
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL,
|
||||
-20
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
|
||||
);
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL,
|
||||
20
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```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:
|
||||
|
||||
Operator Constant | Value
|
||||
------------------------------------------|----------------------
|
||||
AUTOFILTER_COLUMN_RULE_EQUAL | 'equal'
|
||||
AUTOFILTER_COLUMN_RULE_NOTEQUAL | 'notEqual'
|
||||
AUTOFILTER_COLUMN_RULE_GREATERTHAN | 'greaterThan'
|
||||
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.
|
||||
|
||||
![04-04-dynamic-autofilter.png](./images/04-04-dynamic-autofilter.png "")
|
||||
|
||||
Again, we start by specifying a Filter type, this time a DYNAMICFILTER.
|
||||
|
||||
```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.
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_EQUAL,
|
||||
NULL,
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
Operator Constant | Value
|
||||
-----------------------------------------|----------------
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY | 'yesterday'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_TODAY | 'today'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW | 'tomorrow'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE | 'yearToDate'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR | 'thisYear'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER | 'thisQuarter'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH | 'thisMonth'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK | 'thisWeek'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR | 'lastYear'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER | 'lastQuarter'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH | 'lastMonth'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK | 'lastWeek'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR | 'nextYear'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER | 'nextQuarter'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH | 'nextMonth'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK | 'nextWeek'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 | 'M1'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_JANUARY | 'M1'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 | 'M2'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY | 'M2'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 | 'M3'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MARCH | 'M3'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 | 'M4'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_APRIL | 'M4'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 | 'M5'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MAY | 'M5'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 | 'M6'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_JUNE | 'M6'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 | 'M7'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_JULY | 'M7'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 | 'M8'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_AUGUST | 'M8'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 | 'M9'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER | 'M9'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 | 'M10'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER | 'M10'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 | 'M11'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER | 'M11'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 | 'M12'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER | 'M12'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 | 'Q1'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 | 'Q2'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 | 'Q3'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 | 'Q4'
|
||||
AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE | 'aboveAverage'
|
||||
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:
|
||||
|
||||
![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 "")
|
||||
|
||||
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.
|
||||
|
||||
We start by specifying a Filter type, this time a DYNAMICFILTER.
|
||||
|
||||
```php
|
||||
$columnFilter->setFilterType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER
|
||||
);
|
||||
```
|
||||
|
||||
Then we create the rule:
|
||||
|
||||
```php
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT,
|
||||
5,
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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
|
||||
$columnFilter->createRule()
|
||||
->setRule(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE,
|
||||
5,
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM
|
||||
)
|
||||
->setRuleType(
|
||||
\PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter\Column\Rule::AUTOFILTER_RULETYPE_TOPTENFILTER
|
||||
);
|
||||
```
|
||||
|
||||
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
|
||||
---------------------------------------|-------------
|
||||
AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE | 'byValue'
|
||||
AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT | 'byPercent'
|
||||
|
||||
and
|
||||
|
||||
Operator Constant | Value
|
||||
-------------------------------------|----------
|
||||
AUTOFILTER_COLUMN_RULE_TOPTEN_TOP | 'top'
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```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.
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
foreach ($spreadsheet->getActiveSheet()->getRowIterator() as $row) {
|
||||
if ($spreadsheet->getActiveSheet()
|
||||
->getRowDimension($row->getRowIndex())->getVisible()) {
|
||||
echo ' Row number - ' , $row->getRowIndex() , ' ';
|
||||
echo $spreadsheet->getActiveSheet()
|
||||
->getCell(
|
||||
'C'.$row->getRowIndex()
|
||||
)
|
||||
->getValue(), ' ';
|
||||
echo $spreadsheet->getActiveSheet()
|
||||
->getCell(
|
||||
'D'.$row->getRowIndex()
|
||||
)->getFormattedValue(), ' ';
|
||||
echo EOL;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## AutoFilter Sorting
|
||||
|
||||
In MS Excel, Autofiltering also allows the rows to be sorted. This feature is ***not*** supported by PhpSpreadsheet.
|
||||
|
|
@ -1,27 +1,24 @@
|
|||
# PhpSpreadsheet User Documentation – Reading Spreadsheet Files
|
||||
# File Formats
|
||||
|
||||
|
||||
## Spreadsheet 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 Functionality Cross-Reference document (Functionality Cross-Reference.xls) 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][1] or from [http://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/[MS-XLS].pdf][2] (as a downloadable 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 [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).
|
||||
|
||||
### 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][3] 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 [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.
|
||||
|
||||
### 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][4]) 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 ([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.
|
||||
|
||||
### 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][5]). Other information is available from the OpenOffice.org XML File Format web page ([http://xml.openoffice.org/general.html][6]), 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 ([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.
|
||||
|
||||
### SYLK
|
||||
|
||||
|
@ -29,13 +26,14 @@ This is the Microsoft Multiplan Symbolic Link Interchange (SYLK) file format. Mu
|
|||
|
||||
### 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][7]
|
||||
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)
|
||||
|
||||
### 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.
|
||||
|
||||
"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,
|
||||
|
@ -49,12 +47,3 @@ Within these general constraints, many variations are in use. Therefore "CSV" fi
|
|||
|
||||
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.
|
||||
|
||||
|
||||
|
||||
[1]: http://msdn.microsoft.com/en-us/library/cc313154(v=office.12).aspx
|
||||
[2]: http://download.microsoft.com/download/2/4/8/24862317-78F0-4C4B-B355-C7B2C1D997DB/%5bMS-XLS%5d.pdf
|
||||
[3]: http://msdn.microsoft.com/en-us/library/aa140066%28office.10%29.aspx
|
||||
[4]: http://www.ecma-international.org/news/TC45_current_work/TC45_available_docs.htm
|
||||
[5]: http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=office
|
||||
[6]: http://xml.openoffice.org/general.html
|
||||
[7]: http://projects.gnome.org/gnumeric/doc/file-format-gnumeric.shtml
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 453 B After Width: | Height: | Size: 453 B |
Before Width: | Height: | Size: 640 B After Width: | Height: | Size: 640 B |
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 66 KiB |
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 48 KiB |
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 51 KiB |
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 52 KiB |
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 109 KiB |
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 52 KiB |
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
Before Width: | Height: | Size: 31 KiB After Width: | Height: | Size: 31 KiB |
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
Before Width: | Height: | Size: 122 KiB After Width: | Height: | Size: 122 KiB |
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
Before Width: | Height: | Size: 43 KiB After Width: | Height: | Size: 43 KiB |
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 25 KiB |
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 33 KiB |
|
@ -0,0 +1,934 @@
|
|||
# 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:
|
||||
|
||||
- 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.
|
||||
|
||||
## 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.
|
||||
|
||||
```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.
|
||||
|
||||
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.
|
||||
|
||||
```php
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Xls Reader **/
|
||||
$objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\Excel2003XML();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\Ods();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\SYLK();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\Gnumeric();
|
||||
// $objReader = new \PhpOffice\PhpSpreadsheet\Reader\CSV();
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
// $inputFileType = 'Xlsx';
|
||||
// $inputFileType = 'Excel2003XML';
|
||||
// $inputFileType = 'Ods';
|
||||
// $inputFileType = 'SYLK';
|
||||
// $inputFileType = 'Gnumeric';
|
||||
// $inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Identify the type of $inputFileName **/
|
||||
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName);
|
||||
/** Create a new Reader of the type that has been identified **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
```
|
||||
> 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.
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader that we only want to load cell data **/
|
||||
$objReader->setReadDataOnly(true);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
To read a single sheet, you can pass that sheet name as a parameter to the setLoadSheetsOnly() method.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetname = 'Data Sheet #2';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader of which WorkSheets we want to load **/
|
||||
$objReader->setLoadSheetsOnly($sheetname);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetnames = array('Data Sheet #1','Data Sheet #3');
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader of which WorkSheets we want to load **/
|
||||
$objReader->setLoadSheetsOnly($sheetnames);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader to load all Worksheets **/
|
||||
$objReader->setLoadAllSheets();
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
```
|
||||
> See Examples/Reader/exampleReader06.php for a working example of this code.
|
||||
|
||||
Reading Only Named WorkSheets from a 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 |
|
||||
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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetname = 'Data Sheet #3';
|
||||
|
||||
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Read rows 1 to 7 and columns A to E only
|
||||
if ($row >= 1 && $row <= 7) {
|
||||
if (in_array($column,range('A','E'))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create an Instance of our Read Filter **/
|
||||
$filterSubset = new MyReadFilter();
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
$objReader->setReadFilter($filterSubset);
|
||||
/** Load only the rows and columns that match our filter to Spreadsheet **/
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
```php
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
private $_startRow = 0;
|
||||
private $_endRow = 0;
|
||||
private $_columns = array();
|
||||
|
||||
/** Get the list of rows and columns to read */
|
||||
public function __construct($startRow, $endRow, $columns) {
|
||||
$this->_startRow = $startRow;
|
||||
$this->_endRow = $endRow;
|
||||
$this->_columns = $columns;
|
||||
}
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Only read the rows and columns that were configured
|
||||
if ($row >= $this->_startRow && $row <= $this->_endRow) {
|
||||
if (in_array($column,$this->_columns)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example2.xls';
|
||||
|
||||
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class chunkReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
private $_startRow = 0;
|
||||
private $_endRow = 0;
|
||||
|
||||
/** Set the list of rows that we want to read */
|
||||
public function setRows($startRow, $chunkSize) {
|
||||
$this->_startRow = $startRow;
|
||||
$this->_endRow = $startRow + $chunkSize;
|
||||
}
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Only read the heading row, and the configured rows
|
||||
if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Define how many rows we want to read for each "chunk" **/
|
||||
$chunkSize = 2048;
|
||||
/** Create a new Instance of our Read Filter **/
|
||||
$chunkFilter = new chunkReadFilter();
|
||||
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
$objReader->setReadFilter($chunkFilter);
|
||||
|
||||
/** Loop to read our worksheet in "chunk size" blocks **/
|
||||
for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) {
|
||||
/** Tell the Read Filter which rows we want this iteration **/
|
||||
$chunkFilter->setRows($startRow,$chunkSize);
|
||||
/** Load only the rows that match our filter **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
// Do some processing here
|
||||
}
|
||||
```
|
||||
> 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
|
||||
|
||||
### 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 $objReader, then use the loadIntoExisting() method rather than the load() method to actually read the file into that worksheet.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileNames = array('./sampleData/example1.csv',
|
||||
'./sampleData/example2.csv'
|
||||
'./sampleData/example3.csv'
|
||||
);
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Extract the first named file from the array list **/
|
||||
$inputFileName = array_shift($inputFileNames);
|
||||
/** Load the initial file to the first worksheet in a `Spreadsheet` Object **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
/** Set the worksheet title (to the filename that we've loaded) **/
|
||||
$spreadsheet->getActiveSheet()
|
||||
->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
|
||||
|
||||
|
||||
/** Loop through all the remaining files in the list **/
|
||||
foreach($inputFileNames as $sheet => $inputFileName) {
|
||||
/** Increment the worksheet index pointer for the Reader **/
|
||||
$objReader->setSheetIndex($sheet+1);
|
||||
/** Load the current file into a new worksheet in Spreadsheet **/
|
||||
$objReader->loadIntoExisting($inputFileName,$spreadsheet);
|
||||
/** Set the worksheet title (to the filename that we've loaded) **/
|
||||
$spreadsheet->getActiveSheet()
|
||||
->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.
|
||||
|
||||
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 |
|
||||
CSV | YES | HTML | NO
|
||||
|
||||
### 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 $objReader, we can split the CSV file across several individual worksheets.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example2.csv';
|
||||
|
||||
|
||||
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Define how many rows we want to read for each "chunk" **/
|
||||
$chunkSize = 65530;
|
||||
/** Create a new Instance of our Read Filter **/
|
||||
$chunkFilter = new chunkReadFilter();
|
||||
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
/** and that we want to store it in contiguous rows/columns **/
|
||||
|
||||
$objReader->setReadFilter($chunkFilter)
|
||||
->setContiguous(true);
|
||||
|
||||
/** Instantiate a new Spreadsheet object manually **/
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
|
||||
/** Set a sheet index **/
|
||||
$sheet = 0;
|
||||
/** Loop to read our worksheet in "chunk size" blocks **/
|
||||
/** $startRow is set to 2 initially because we always read the headings in row #1 **/
|
||||
for ($startRow = 2; $startRow <= 1000000; $startRow += $chunkSize) {
|
||||
/** Tell the Read Filter which rows we want to read this loop **/
|
||||
$chunkFilter->setRows($startRow,$chunkSize);
|
||||
|
||||
/** Increment the worksheet index pointer for the Reader **/
|
||||
$objReader->setSheetIndex($sheet);
|
||||
/** Load only the rows that match our filter into a new worksheet **/
|
||||
$objReader->loadIntoExisting($inputFileName,$spreadsheet);
|
||||
/** Set the worksheet title for the sheet that we've justloaded) **/
|
||||
/** and increment the sheet index as well **/
|
||||
$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.
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example1.tsv';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/ $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Set the delimiter to a TAB character **/
|
||||
$objReader->setDelimiter("\t");
|
||||
// $objReader->setDelimiter('|');
|
||||
|
||||
/** Load the file to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```php
|
||||
/** Tell PhpSpreadsheet that we want to use the Advanced Value Binder **/
|
||||
\PhpOffice\PhpSpreadsheet\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
|
||||
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example1.tsv';
|
||||
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
$objReader->setDelimiter("\t");
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
```
|
||||
> 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
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader that we only want to load cell data **/
|
||||
$objReader->setReadDataOnly(true);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
To read a single sheet, you can pass that sheet name as a parameter to the setLoadSheetsOnly() method.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetname = 'Data Sheet #2';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader of which WorkSheets we want to load **/
|
||||
$objReader->setLoadSheetsOnly($sheetname);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetnames = array('Data Sheet #1','Data Sheet #3');
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader of which WorkSheets we want to load **/
|
||||
$objReader->setLoadSheetsOnly($sheetnames);
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Advise the Reader to load all Worksheets **/
|
||||
$objReader->setLoadAllSheets();
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
```
|
||||
> See Examples/Reader/exampleReader06.php for a working example of this code.
|
||||
|
||||
Reading Only Named WorkSheets from a 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 |
|
||||
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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example1.xls';
|
||||
$sheetname = 'Data Sheet #3';
|
||||
|
||||
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Read rows 1 to 7 and columns A to E only
|
||||
if ($row >= 1 && $row <= 7) {
|
||||
if (in_array($column,range('A','E'))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create an Instance of our Read Filter **/
|
||||
$filterSubset = new MyReadFilter();
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
$objReader->setReadFilter($filterSubset);
|
||||
/** Load only the rows and columns that match our filter to Spreadsheet **/
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
```php
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
private $_startRow = 0;
|
||||
private $_endRow = 0;
|
||||
private $_columns = array();
|
||||
|
||||
/** Get the list of rows and columns to read */
|
||||
public function __construct($startRow, $endRow, $columns) {
|
||||
$this->_startRow = $startRow;
|
||||
$this->_endRow = $endRow;
|
||||
$this->_columns = $columns;
|
||||
}
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Only read the rows and columns that were configured
|
||||
if ($row >= $this->_startRow && $row <= $this->_endRow) {
|
||||
if (in_array($column,$this->_columns)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'Xls';
|
||||
$inputFileName = './sampleData/example2.xls';
|
||||
|
||||
|
||||
/** Define a Read Filter class implementing \PhpOffice\PhpSpreadsheet\Reader\IReadFilter */
|
||||
class chunkReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
|
||||
{
|
||||
private $_startRow = 0;
|
||||
private $_endRow = 0;
|
||||
|
||||
/** Set the list of rows that we want to read */
|
||||
public function setRows($startRow, $chunkSize) {
|
||||
$this->_startRow = $startRow;
|
||||
$this->_endRow = $startRow + $chunkSize;
|
||||
}
|
||||
|
||||
public function readCell($column, $row, $worksheetName = '') {
|
||||
// Only read the heading row, and the configured rows
|
||||
if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Define how many rows we want to read for each "chunk" **/
|
||||
$chunkSize = 2048;
|
||||
/** Create a new Instance of our Read Filter **/
|
||||
$chunkFilter = new chunkReadFilter();
|
||||
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
$objReader->setReadFilter($chunkFilter);
|
||||
|
||||
/** Loop to read our worksheet in "chunk size" blocks **/
|
||||
for ($startRow = 2; $startRow <= 65536; $startRow += $chunkSize) {
|
||||
/** Tell the Read Filter which rows we want this iteration **/
|
||||
$chunkFilter->setRows($startRow,$chunkSize);
|
||||
/** Load only the rows that match our filter **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
// Do some processing here
|
||||
}
|
||||
```
|
||||
> 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
|
||||
|
||||
### 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 $objReader, then use the loadIntoExisting() method rather than the load() method to actually read the file into that worksheet.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileNames = array('./sampleData/example1.csv',
|
||||
'./sampleData/example2.csv'
|
||||
'./sampleData/example3.csv'
|
||||
);
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Extract the first named file from the array list **/
|
||||
$inputFileName = array_shift($inputFileNames);
|
||||
/** Load the initial file to the first worksheet in a `Spreadsheet` Object **/
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
/** Set the worksheet title (to the filename that we've loaded) **/
|
||||
$spreadsheet->getActiveSheet()
|
||||
->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
|
||||
|
||||
|
||||
/** Loop through all the remaining files in the list **/
|
||||
foreach($inputFileNames as $sheet => $inputFileName) {
|
||||
/** Increment the worksheet index pointer for the Reader **/
|
||||
$objReader->setSheetIndex($sheet+1);
|
||||
/** Load the current file into a new worksheet in Spreadsheet **/
|
||||
$objReader->loadIntoExisting($inputFileName,$spreadsheet);
|
||||
/** Set the worksheet title (to the filename that we've loaded) **/
|
||||
$spreadsheet->getActiveSheet()
|
||||
->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.
|
||||
|
||||
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 |
|
||||
CSV | YES | HTML | NO
|
||||
|
||||
### 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 $objReader, we can split the CSV file across several individual worksheets.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example2.csv';
|
||||
|
||||
|
||||
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
|
||||
/** Create a new Reader of the type defined in $inputFileType **/
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
|
||||
/** Define how many rows we want to read for each "chunk" **/
|
||||
$chunkSize = 65530;
|
||||
/** Create a new Instance of our Read Filter **/
|
||||
$chunkFilter = new chunkReadFilter();
|
||||
|
||||
/** Tell the Reader that we want to use the Read Filter **/
|
||||
/** and that we want to store it in contiguous rows/columns **/
|
||||
|
||||
$objReader->setReadFilter($chunkFilter)
|
||||
->setContiguous(true);
|
||||
|
||||
/** Instantiate a new Spreadsheet object manually **/
|
||||
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
|
||||
|
||||
/** Set a sheet index **/
|
||||
$sheet = 0;
|
||||
/** Loop to read our worksheet in "chunk size" blocks **/
|
||||
/** $startRow is set to 2 initially because we always read the headings in row #1 **/
|
||||
for ($startRow = 2; $startRow <= 1000000; $startRow += $chunkSize) {
|
||||
/** Tell the Read Filter which rows we want to read this loop **/
|
||||
$chunkFilter->setRows($startRow,$chunkSize);
|
||||
|
||||
/** Increment the worksheet index pointer for the Reader **/
|
||||
$objReader->setSheetIndex($sheet);
|
||||
/** Load only the rows that match our filter into a new worksheet **/
|
||||
$objReader->loadIntoExisting($inputFileName,$spreadsheet);
|
||||
/** Set the worksheet title for the sheet that we've justloaded) **/
|
||||
/** and increment the sheet index as well **/
|
||||
$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.
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
```php
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example1.tsv';
|
||||
|
||||
/** Create a new Reader of the type defined in $inputFileType **/ $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
/** Set the delimiter to a TAB character **/
|
||||
$objReader->setDelimiter("\t");
|
||||
// $objReader->setDelimiter('|');
|
||||
|
||||
/** Load the file to a Spreadsheet Object **/
|
||||
$spreadsheet = $objReader->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:
|
||||
|
||||
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 |
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```php
|
||||
/** Tell PhpSpreadsheet that we want to use the Advanced Value Binder **/
|
||||
\PhpOffice\PhpSpreadsheet\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
|
||||
|
||||
$inputFileType = 'CSV';
|
||||
$inputFileName = './sampleData/example1.tsv';
|
||||
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
$objReader->setDelimiter("\t");
|
||||
$spreadsheet = $objReader->load($inputFileName);
|
||||
```
|
||||
> 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
|
||||
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.
|
||||
|
||||
The PhpSpreadsheet Readers throw a \PhpOffice\PhpSpreadsheet\Reader\Exception.
|
||||
|
||||
```php
|
||||
$inputFileName = './sampleData/example-1.xls';
|
||||
|
||||
try {
|
||||
/** Load $inputFileName to a Spreadsheet Object **/
|
||||
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
|
||||
} catch(\PhpOffice\PhpSpreadsheet\Reader\Exception $e) {
|
||||
die('Error loading file: '.$e->getMessage());
|
||||
}
|
||||
```
|
||||
> 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.
|
||||
|
||||
### listWorksheetNames
|
||||
|
||||
The `listWorksheetNames()` method returns a simple array listing each worksheet name within the workbook:
|
||||
|
||||
```php
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
$worksheetNames = $objReader->listWorksheetNames($inputFileName);
|
||||
|
||||
echo '<h3>Worksheet Names</h3>';
|
||||
echo '<ol>';
|
||||
foreach ($worksheetNames as $worksheetName) {
|
||||
echo '<li>', $worksheetName, '</li>';
|
||||
}
|
||||
echo '</ol>';
|
||||
```
|
||||
> 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:
|
||||
|
||||
```php
|
||||
$objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
|
||||
|
||||
$worksheetData = $objReader->listWorksheetInfo($inputFileName);
|
||||
|
||||
echo '<h3>Worksheet Information</h3>';
|
||||
echo '<ol>';
|
||||
foreach ($worksheetData as $worksheet) {
|
||||
echo '<li>', $worksheet['worksheetName'], '<br />';
|
||||
echo 'Rows: ', $worksheet['totalRows'],
|
||||
' Columns: ', $worksheet['totalColumns'], '<br />';
|
||||
echo 'Cell Range: A1:',
|
||||
$worksheet['lastColumnLetter'], $worksheet['totalRows'];
|
||||
echo '</li>';
|
||||
}
|
||||
echo '</ol>';
|
||||
```
|
||||
> See Examples/Reader/exampleReader19.php for a working example of this code.
|
|
@ -1,12 +1,10 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
## PhpSpreadsheet recipes
|
||||
# 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.
|
||||
|
||||
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
|
||||
## 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.
|
||||
|
||||
|
@ -25,7 +23,7 @@ $spreadsheet->getProperties()
|
|||
->setCategory("Test result file");
|
||||
```
|
||||
|
||||
### Setting a spreadsheet's active sheet
|
||||
## Setting a spreadsheet's active sheet
|
||||
|
||||
The following line of code sets the active sheet index to the first sheet:
|
||||
|
||||
|
@ -41,7 +39,7 @@ $spreadsheet->setActiveSheetIndexByName('DataSheet')
|
|||
|
||||
will change the currently active sheet to the worksheet called "DataSheet".
|
||||
|
||||
### Write a date or time into a cell
|
||||
## 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.
|
||||
|
||||
|
@ -87,7 +85,7 @@ __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.
|
||||
|
||||
### Write a formula into a cell
|
||||
## 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:
|
||||
|
||||
|
@ -129,7 +127,7 @@ If you need the calculated value of a cell, use the following code. This is furt
|
|||
$value = $spreadsheet->getActiveSheet()->getCell('B8')->getCalculatedValue();
|
||||
```
|
||||
|
||||
### Locale Settings for Formulae
|
||||
## 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:
|
||||
|
||||
|
@ -181,7 +179,7 @@ At present, the following locale settings are supported:
|
|||
Swedish | Svenska | sv
|
||||
Turkish | Türkçe | tr
|
||||
|
||||
### Write a newline character "\n" in a cell (ALT+"Enter")
|
||||
## 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.
|
||||
|
||||
|
@ -208,7 +206,7 @@ $spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
|
|||
|
||||
Read more about AdvancedValueBinder.php elsewhere.
|
||||
|
||||
### Explicitly set a cell's datatype
|
||||
## 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:
|
||||
|
||||
|
@ -220,7 +218,7 @@ $spreadsheet->getActiveSheet()->getCell('A1')
|
|||
);
|
||||
```
|
||||
|
||||
### Change a cell into a clickable URL
|
||||
## Change a cell into a clickable URL
|
||||
|
||||
You can make a cell a clickable URL by setting its hyperlink property:
|
||||
|
||||
|
@ -236,9 +234,9 @@ $spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
|
|||
$spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl("sheet://'Sheetname'!A1");
|
||||
```
|
||||
|
||||
### Setting Printer Options for Excel files
|
||||
## Setting Printer Options for Excel files
|
||||
|
||||
#### Setting a worksheet's page orientation and size
|
||||
### 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:
|
||||
|
||||
|
@ -251,7 +249,7 @@ $spreadsheet->getActiveSheet()->getPageSetup()
|
|||
|
||||
Note that there are additional page settings available. Please refer to the API documentation for all possible options.
|
||||
|
||||
#### Page Setup: Scaling 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.
|
||||
|
||||
|
@ -266,7 +264,7 @@ Default values in PhpSpreadsheet correspond to default values in MS Office Excel
|
|||
setFitToWidth(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-width
|
||||
setFitToHeight(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-height
|
||||
|
||||
##### Example
|
||||
#### Example
|
||||
|
||||
Here is how to fit to 1 page wide by infinite pages tall:
|
||||
|
||||
|
@ -279,7 +277,7 @@ As you can see, it is not necessary to call setFitToPage(TRUE) since setFitToWid
|
|||
|
||||
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
|
||||
### Page margins
|
||||
|
||||
To set page margins for a worksheet, use this code:
|
||||
|
||||
|
@ -294,7 +292,7 @@ Note that the margin values are specified in inches.
|
|||
|
||||
![08-page-setup-margins.png](./images/08-page-setup-margins.png "")
|
||||
|
||||
#### Center a page horizontally/vertically
|
||||
### Center a page horizontally/vertically
|
||||
|
||||
To center a page horizontally/vertically, you can use the following code:
|
||||
|
||||
|
@ -303,7 +301,7 @@ $spreadsheet->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);
|
|||
$spreadsheet->getActiveSheet()->getPageSetup()->setVerticalCentered(false);
|
||||
```
|
||||
|
||||
#### Setting the print header and footer of a worksheet
|
||||
### 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:
|
||||
|
||||
|
@ -383,7 +381,7 @@ var_dump($objWorksheet->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.
|
||||
|
||||
#### Setting printing breaks on a row or column
|
||||
### 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.
|
||||
|
||||
|
@ -397,13 +395,13 @@ The following line of code sets a print break on column D:
|
|||
$spreadsheet->getActiveSheet()->setBreak( 'D10' , \PhpOffice\PhpSpreadsheet\Worksheet::BREAK_COLUMN );
|
||||
```
|
||||
|
||||
#### Show/hide gridlines when printing
|
||||
### Show/hide gridlines when printing
|
||||
|
||||
To show/hide gridlines when printing, use the following code:
|
||||
|
||||
$spreadsheet->getActiveSheet()->setShowGridlines(true);
|
||||
|
||||
#### Setting rows/columns to repeat at top/left
|
||||
### 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:
|
||||
|
||||
|
@ -411,7 +409,7 @@ PhpSpreadsheet can repeat specific rows/cells at top/left of a page. The followi
|
|||
$spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
|
||||
```
|
||||
|
||||
#### Specify printing area
|
||||
### Specify printing area
|
||||
|
||||
To specify a worksheet's printing area, use the following code:
|
||||
|
||||
|
@ -425,9 +423,9 @@ There can also be multiple printing areas in a single worksheet:
|
|||
$spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5,G4:M20');
|
||||
```
|
||||
|
||||
### Styles
|
||||
## Styles
|
||||
|
||||
#### Formatting cells
|
||||
### 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:
|
||||
|
||||
|
@ -501,7 +499,7 @@ This alternative method using arrays should be faster in terms of execution when
|
|||
|
||||
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
|
||||
### 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.
|
||||
|
||||
|
@ -551,7 +549,7 @@ var_dump($spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()->getF
|
|||
|
||||
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
|
||||
### Alignment and wrap text
|
||||
|
||||
Let's set vertical alignment to the top for cells A1:D4
|
||||
|
||||
|
@ -567,7 +565,7 @@ $spreadsheet->getActiveSheet()->getStyle('A1:D4')
|
|||
->getAlignment()->setWrapText(true);
|
||||
```
|
||||
|
||||
#### Setting the default style of a workbook
|
||||
### 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:
|
||||
|
||||
|
@ -576,7 +574,7 @@ $spreadsheet->getDefaultStyle()->getFont()->setName('Arial');
|
|||
$spreadsheet->getDefaultStyle()->getFont()->setSize(8);
|
||||
```
|
||||
|
||||
#### Styling cell borders
|
||||
### 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.
|
||||
|
||||
|
@ -599,23 +597,19 @@ Note that the border outline is applied to the rectangular selection B2:G8 as a
|
|||
|
||||
You can achieve any border effect by using just the 5 basic borders and operating on a single cell at a time:
|
||||
|
||||
Array key | Maps to property
|
||||
----------|------------------
|
||||
left | getLeft()
|
||||
right | getRight()
|
||||
top | getTop()
|
||||
bottom | getBottom()
|
||||
diagonal | getDiagonal()
|
||||
- left
|
||||
- right
|
||||
- top
|
||||
- bottom
|
||||
- diagonal
|
||||
|
||||
Additional shortcut borders come in handy like in the example above. These are the shortcut borders available:
|
||||
|
||||
Array key | Maps to property
|
||||
-----------|------------------
|
||||
allborders | getAllBorders()
|
||||
outline | getOutline()
|
||||
inside | getInside()
|
||||
vertical | getVertical()
|
||||
horizontal | getHorizontal()
|
||||
- allborders
|
||||
- outline
|
||||
- inside
|
||||
- vertical
|
||||
- horizontal
|
||||
|
||||
|
||||
|
||||
|
@ -627,7 +621,101 @@ If you simultaneously set e.g. allborders and vertical, then we have "overlappin
|
|||
|
||||
This border hierarchy can be utilized to achieve various effects in an easy manner.
|
||||
|
||||
### Conditional formatting a cell
|
||||
### 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.
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style__
|
||||
|
||||
Array key | Maps to property
|
||||
-------------|-------------------
|
||||
fill | getFill()
|
||||
font | getFont()
|
||||
borders | getBorders()
|
||||
alignment | getAlignment()
|
||||
numberformat | getNumberFormat()
|
||||
protection | getProtection()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Fill__
|
||||
|
||||
Array key | Maps to property
|
||||
-----------|-------------------
|
||||
type | setFillType()
|
||||
rotation | setRotation()
|
||||
startcolor | getStartColor()
|
||||
endcolor | getEndColor()
|
||||
color | getStartColor()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Font__
|
||||
|
||||
Array key | Maps to property
|
||||
------------|-------------------
|
||||
name | setName()
|
||||
bold | setBold()
|
||||
italic | setItalic()
|
||||
underline | setUnderline()
|
||||
strike | setStrikethrough()
|
||||
color | getColor()
|
||||
size | setSize()
|
||||
superScript | setSuperScript()
|
||||
subScript | setSubScript()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Borders__
|
||||
|
||||
Array key | Maps to property
|
||||
------------------|-------------------
|
||||
allborders | getLeft(); getRight(); getTop(); getBottom()
|
||||
left | getLeft()
|
||||
right | getRight()
|
||||
top | getTop()
|
||||
bottom | getBottom()
|
||||
diagonal | getDiagonal()
|
||||
vertical | getVertical()
|
||||
horizontal | getHorizontal()
|
||||
diagonaldirection | setDiagonalDirection()
|
||||
outline | setOutline()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Border__
|
||||
|
||||
Array key | Maps to property
|
||||
----------|-------------------
|
||||
style | setBorderStyle()
|
||||
color | getColor()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\Alignment__
|
||||
|
||||
Array key | Maps to property
|
||||
------------|-------------------
|
||||
horizontal | setHorizontal()
|
||||
vertical | setVertical()
|
||||
rotation | setTextRotation()
|
||||
wrap | setWrapText()
|
||||
shrinkToFit | setShrinkToFit()
|
||||
indent | setIndent()
|
||||
|
||||
|
||||
__\PhpOffice\PhpSpreadsheet\Style\NumberFormat__
|
||||
|
||||
Array key | Maps to property
|
||||
----------|-------------------
|
||||
code | setFormatCode()
|
||||
|
||||
|
||||
__\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.
|
||||
|
||||
|
@ -665,7 +753,7 @@ $spreadsheet->getActiveSheet()
|
|||
);
|
||||
```
|
||||
|
||||
### Add a comment to a cell
|
||||
## 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:
|
||||
|
||||
|
@ -687,7 +775,7 @@ $spreadsheet->getActiveSheet()
|
|||
|
||||
![08-cell-comment.png](./images/08-cell-comment.png "")
|
||||
|
||||
### Apply autofilter to a range of cells
|
||||
## Apply autofilter to a range of cells
|
||||
|
||||
To apply an autofilter to a range of cells, use the following code:
|
||||
|
||||
|
@ -698,7 +786,7 @@ $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...
|
||||
|
||||
### Setting security on a spreadsheet
|
||||
## Setting security on a spreadsheet
|
||||
|
||||
Excel offers 3 levels of "protection": document security, sheet security and cell security.
|
||||
|
||||
|
@ -739,7 +827,7 @@ __Make sure you enable worksheet protection if you need any of the worksheet pro
|
|||
$spreadsheet->getActiveSheet()->getProtection()->setSheet(true);
|
||||
```
|
||||
|
||||
### Setting data validation on a cell
|
||||
## 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), ...
|
||||
|
||||
|
@ -789,7 +877,7 @@ If you need data validation on multiple cells, one can clone the ruleset:
|
|||
$spreadsheet->getActiveSheet()->getCell('B8')->setDataValidation(clone $objValidation);
|
||||
```
|
||||
|
||||
### Setting a column's width
|
||||
## Setting a column's width
|
||||
|
||||
A column's width can be set using the following code:
|
||||
|
||||
|
@ -807,7 +895,7 @@ $spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
|
|||
|
||||
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
|
||||
## 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.
|
||||
|
||||
|
@ -816,7 +904,7 @@ $spreadsheet->getActiveSheet()->getColumnDimension('C')->setVisible(true);
|
|||
$spreadsheet->getActiveSheet()->getColumnDimension('D')->setVisible(false);
|
||||
```
|
||||
|
||||
### Group/outline a column
|
||||
## Group/outline a column
|
||||
|
||||
To group/outline a column, you can use the following code:
|
||||
|
||||
|
@ -839,7 +927,7 @@ You can instruct PhpSpreadsheet to add a summary to the right (default), or to t
|
|||
$spreadsheet->getActiveSheet()->setShowSummaryRight(false);
|
||||
```
|
||||
|
||||
### Setting a row's height
|
||||
## Setting a row's height
|
||||
|
||||
A row's height can be set using the following code:
|
||||
|
||||
|
@ -849,7 +937,7 @@ $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.
|
||||
|
||||
### Show/hide a 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.
|
||||
|
||||
|
@ -859,7 +947,7 @@ $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.
|
||||
|
||||
### Group/outline a row
|
||||
## Group/outline a row
|
||||
|
||||
To group/outline a row, you can use the following code:
|
||||
|
||||
|
@ -896,7 +984,7 @@ You can instruct PhpSpreadsheet to add a summary below the collapsible rows (def
|
|||
$spreadsheet->getActiveSheet()->setShowSummaryBelow(false);
|
||||
```
|
||||
|
||||
### Merge/unmerge cells
|
||||
## 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:
|
||||
|
||||
|
@ -910,7 +998,7 @@ Removing a merge can be done using the unmergeCells method:
|
|||
$spreadsheet->getActiveSheet()->unmergeCells('A18:E22');
|
||||
```
|
||||
|
||||
### Inserting rows/columns
|
||||
## Inserting rows/columns
|
||||
|
||||
You can insert/remove rows/columns at a specific position. The following code inserts 2 new rows, right before row 7:
|
||||
|
||||
|
@ -918,7 +1006,7 @@ You can insert/remove rows/columns at a specific position. The following code in
|
|||
$spreadsheet->getActiveSheet()->insertNewRowBefore(7, 2);
|
||||
```
|
||||
|
||||
### Add a drawing to a worksheet
|
||||
## 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:
|
||||
|
||||
|
@ -971,7 +1059,7 @@ $objDrawing->setHeight(36);
|
|||
$objDrawing->setWorksheet($spreadsheet->getActiveSheet());
|
||||
```
|
||||
|
||||
### Reading Images from a worksheet
|
||||
## 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.
|
||||
|
||||
|
@ -1013,7 +1101,7 @@ foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) {
|
|||
}
|
||||
```
|
||||
|
||||
### Add rich text to a cell
|
||||
## 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:
|
||||
|
||||
|
@ -1030,7 +1118,7 @@ $objRichText->createText(', unless specified otherwise on the invoice.');
|
|||
$spreadsheet->getActiveSheet()->getCell('A18')->setValue($objRichText);
|
||||
```
|
||||
|
||||
### Define a named range
|
||||
## Define a named range
|
||||
|
||||
PhpSpreadsheet supports the definition of named ranges. These can be defined using the following code:
|
||||
|
||||
|
@ -1049,20 +1137,20 @@ $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonLN'
|
|||
|
||||
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
|
||||
## 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:
|
||||
|
||||
1. Create your PhpSpreadsheet spreadsheet
|
||||
2. Output HTTP headers for the type of document you wish to output
|
||||
3. Use the PHPExcel_Writer_* of your choice, and save to "php://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.
|
||||
|
||||
#### HTTP headers
|
||||
### HTTP headers
|
||||
|
||||
Example of a script redirecting an Excel 2007 file to the client's browser:
|
||||
|
||||
|
@ -1094,10 +1182,10 @@ $objWriter->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 <?php tag and at most one line break after the closing ?> 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.
|
||||
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 `<?php` tag and at most one line break after the closing `?>` 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
|
||||
## Setting the default column width
|
||||
|
||||
Default column width can be set using the following code:
|
||||
|
||||
|
@ -1105,7 +1193,7 @@ Default column width can be set using the following code:
|
|||
$spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);
|
||||
```
|
||||
|
||||
### Setting the default row height
|
||||
## Setting the default row height
|
||||
|
||||
Default row height can be set using the following code:
|
||||
|
||||
|
@ -1113,7 +1201,7 @@ Default row height can be set using the following code:
|
|||
$spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
|
||||
```
|
||||
|
||||
### Add a GD drawing to a worksheet
|
||||
## 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.
|
||||
|
||||
|
@ -1136,7 +1224,7 @@ $objDrawing->setHeight(36);
|
|||
$objDrawing->setWorksheet($spreadsheet->getActiveSheet());
|
||||
```
|
||||
|
||||
### Setting worksheet zoom level
|
||||
## Setting worksheet zoom level
|
||||
|
||||
To set a worksheet's zoom level, the following code can be used:
|
||||
|
||||
|
@ -1144,9 +1232,9 @@ To set a worksheet's zoom level, the following code can be used:
|
|||
$spreadsheet->getActiveSheet()->getSheetView()->setZoomScale(75);
|
||||
```
|
||||
|
||||
Note that zoom level should be in range 10 – 400.
|
||||
Note that zoom level should be in range 10 - 400.
|
||||
|
||||
### Sheet tab color
|
||||
## Sheet tab color
|
||||
|
||||
Sometimes you want to set a color for sheet tab. For example you can have a red sheet tab:
|
||||
|
||||
|
@ -1154,7 +1242,7 @@ Sometimes you want to set a color for sheet tab. For example you can have a red
|
|||
$objWorksheet->getTabColor()->setRGB('FF0000');
|
||||
```
|
||||
|
||||
### Creating worksheets in a workbook
|
||||
## Creating worksheets in a workbook
|
||||
|
||||
If you need to create more worksheets in the workbook, here is how:
|
||||
|
||||
|
@ -1165,7 +1253,7 @@ $objWorksheet1->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.
|
||||
|
||||
### Hidden worksheets (Sheet states)
|
||||
## Hidden worksheets (Sheet states)
|
||||
|
||||
Set a worksheet to be __hidden__ using this code:
|
||||
|
||||
|
@ -1176,19 +1264,18 @@ $spreadsheet->getActiveSheet()
|
|||
|
||||
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.
|
||||
|
||||
### Right-to-left worksheet
|
||||
## 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.
|
||||
|
||||
```php
|
||||
// right-to-left worksheet
|
||||
$spreadsheet->getActiveSheet()
|
||||
->setRightToLeft(true);
|
||||
$spreadsheet->getActiveSheet()->setRightToLeft(true);
|
||||
```
|
||||
|
|
@ -1,11 +1,8 @@
|
|||
# PhpSpreadsheet Developer Documentation
|
||||
|
||||
|
||||
## Configuration Settings
|
||||
# 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.
|
||||
|
||||
### Cell Caching
|
||||
## 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.
|
||||
|
||||
|
@ -23,23 +20,23 @@ A separate cache is maintained for each individual worksheet, and is automatical
|
|||
|
||||
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.
|
||||
|
||||
#### \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.
|
||||
|
||||
#### \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.
|
||||
|
||||
#### \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.
|
||||
|
||||
#### \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.
|
||||
|
||||
|
@ -53,7 +50,7 @@ $cacheSettings = array(
|
|||
|
||||
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.
|
||||
|
||||
|
@ -67,7 +64,7 @@ $cacheSettings = array(
|
|||
|
||||
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.
|
||||
|
||||
|
@ -81,7 +78,7 @@ $cacheSettings = array(
|
|||
|
||||
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.
|
||||
|
||||
|
@ -99,7 +96,7 @@ $cacheSettings = array(
|
|||
|
||||
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.
|
||||
|
||||
|
@ -113,16 +110,16 @@ $cacheSettings = array(
|
|||
|
||||
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.
|
||||
|
||||
#### \PhpOffice\PhpSpreadsheet\CachedObjectStorageFactory::CACHE_TO_SQLITE3;
|
||||
### \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
|
||||
## 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:
|
||||
|