documentation markdown

This commit is contained in:
Mark Baker 2013-05-17 17:49:12 +01:00
parent e74b1e08f8
commit 1c98aaa76a
6 changed files with 391 additions and 297 deletions

View File

@ -0,0 +1,357 @@
# PHPExcel Developer Documentation
## Accessing cells
Accessing cells in a PHPExcel worksheet 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
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'PHPExcel');
// Set cell A2 with a numeric value
$objPHPExcel->getActiveSheet()->setCellValue('A2', 12345.6789);
// Set cell A3 with a boolean value
$objPHPExcel->getActiveSheet()->setCellValue('A3', TRUE);
// Set cell A4 with a formula
$objPHPExcel->getActiveSheet()->setCellValue(
'A4',
'=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))'
);
```
#### Setting a date and/or time 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 = PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow );
// Set cell A6 with the Excel date/time value
$objPHPExcel->getActiveSheet()->setCellValue(
'A6',
$excelDateValue
);
// Set the number format mask so that the excel timestamp will be displayed as a human-readable date/time
$objPHPExcel->getActiveSheet()->getStyle('A6')
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME
);
```
#### Setting a number with leading zeroes
By default, PHPExcel will automatically detect the value type and set it to the appropriate Excel 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 PHPExcel 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 PHPExcel it should be treated as a string
$objPHPExcel->getActiveSheet()->setCellValueExplicit(
'A8',
"01513789642",
PHPExcel_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
$objPHPExcel->getActiveSheet()->setCellValue('A9', 1513789642);
// Set a number format mask to display the value as 11 digits with leading zeroes
$objPHPExcel->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
$objPHPExcel->getActiveSheet()->setCellValue('A10', 1513789642);
// Set a number format mask to display the value as 11 digits with leading zeroes
$objPHPExcel->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 (Excel2007 and Excel5).
### 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),
);
$objPHPExcel->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');
$objPHPExcel->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);
$objPHPExcel->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 = $objPHPExcel->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 = $objPHPExcel->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 = $objPHPExcel->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
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 5, 'PHPExcel');
```
**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 cells value can be read again using the following line of code:
```php
// Get the value fom cell B5
$cellValue = $objPHPExcel->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 = $objPHPExcel->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 = $objPHPExcel->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 = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(TRUE);
$objPHPExcel = $objReader->load("test.xlsx");
$objWorksheet = $objPHPExcel->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 PHPExcel 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 = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(TRUE);
$objPHPExcel = $objReader->load("test.xlsx");
$objWorksheet = $objPHPExcel->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 = PHPExcel_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 = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(TRUE);
$objPHPExcel = $objReader->load("test.xlsx");
$objWorksheet = $objPHPExcel->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, PHPExcel uses a default PHPExcel_Cell_IValueBinder implementation (PHPExcel_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 PHPExcel can be modified, allowing easier data entry. For example, a PHPExcel_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 PHPExcel:
```php
/** PHPExcel */
require_once 'PHPExcel.php';
// Set value binder
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// ...
// Add some data, resembling some different data types
$objPHPExcel->getActiveSheet()->setCellValue('A4', 'Percentage value:');
// Converts the string value to 0.1 and sets percentage cell style
$objPHPExcel->getActiveSheet()->setCellValue('B4', '10%');
$objPHPExcel->getActiveSheet()->setCellValue('A5', 'Date/time value:');
// Converts the string value to an Excel datestamp and sets the date format cell style
$objPHPExcel->getActiveSheet()->setCellValue('B5', '21 December 1983');
```
__Creating your own value binder is easy.__
When advanced value binding is required, you can implement the PHPExcel_Cell_IValueBinder interface or extend the PHPExcel_Cell_DefaultValueBinder or PHPExcel_Cell_AdvancedValueBinder classes.

View File

@ -1,307 +1,59 @@
# PHPExcel Developer Documentation # PHPExcel Developer Documentation
# Creating a spreadsheet
## The PHPExcel class
The PHPExcel class is the core of PHPExcel. It contains references to the contained worksheets, document security settings and document meta data.
To simplify the PHPExcel concept: the PHPExcel 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 PHPExcel object are described fully in the “PHPExcel User Documentation - Reading Spreadsheet Filesâ€<C3A2> document.
$inputFileName = './sampleData/example1.xls';
/** Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = PHPExcel_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 PHPExcel object.
/** Create a new PHPExcel Object  **/
$objPHPExcel = new PHPExcel();
A new workbook will always be created with a single worksheet.
## Configuration Settings
Once you have included the PHPExcel files in your script, but before instantiating a PHPExcel 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
PHPExcel 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 PHPExcel to maintain the cell objects in a smaller size of memory, on disk, or in APC, memcache or Wincache, rather than in PHP memory. This allows you to reduce the memory usage for large workbooks, although at a cost of speed to access cell data.
By default, PHPExcel still holds all cell objects in memory, but you can specify alternatives. To enable cell caching, you must call the PHPExcel_Settings::setCacheStorageMethod() method, passing in the caching method that you wish to use.
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
setCacheStorageMethod() will return a boolean true on success, false on failure (for example if trying to cache to APC when APC is not enabled).
A separate cache is maintained for each individual worksheet, and is automatically created when the worksheet is instantiated based on the caching method and settings that you have configured. You cannot change the configuration settings once you have started to read a workbook, or have created your first worksheet.
Currently, the following caching methods are available.
PHPExcel_CachedObjectStorageFactory::cache_in_memory;
The default. If you don’t initialise any caching method, then this is the method that PHPExcel will use. Cell objects are maintained in PHP memory as at present.
PHPExcel_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.
PHPExcel_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.
PHPExcel_CachedObjectStorageFactory::cache_igbinary;
Uses PHP’s igbinary extension (if it’s available) to serialize cell objects in memory. This is normally faster and uses less memory than standard PHP serialization, but isn’t available in most hosting environments.
PHPExcel_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, PHPExcel will use PHP’s temp directory for the cache file, but you can specify a different directory when initialising cache_to_discISAM.
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_discISAM;
$cacheSettings = array( 'dir' => '/usr/local/tmp'
);
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
The temporary disk file is automatically deleted when your script terminates.
PHPExcel_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.
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array( 'memoryCacheSize' => '8MB'
);
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
The php://temp file is automatically deleted when your script terminates.
PHPExcel_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.
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_APC;
$cacheSettings = array( 'cacheTime' => 600
);
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
When your script terminates all entries will be cleared from APC, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
PHPExcel_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.
By default, PHPExcel looks for a memcache server on localhost at port 11211. It also sets a memcache timeout limit of 600 seconds. If you are running memcache on a different server or port, then you can change these defaults when you initialise cache_to_memcache:
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_memcache;
$cacheSettings = array( 'memcacheServer' => 'localhost',
'memcachePort' => 11211,
'cacheTime' => 600
);
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
When your script terminates all entries will be cleared from memcache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
PHPExcel_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.
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_wincache;
$cacheSettings = array( 'cacheTime' => 600
);
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
When your script terminates all entries will be cleared from Wincache, regardless of the cacheTime value, so it cannot be used for persistent storage using this mechanism.
PHPExcel_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 – making this the most memory-efficient of the cell caching methods.
PHPExcel_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 – making this the most memory-efficient of the cell caching methods.
### Language/Locale
Some localisation elements have been included in PHPExcel. You can set a locale by changing the settings. To set the locale to Brazilian Portuguese you would use:
$locale = 'pt_br';
$validLocale = PHPExcel_Settings::setLocale($locale);
if (!$validLocale) {
echo 'Unable to set locale to '.$locale." - reverting to en_us<br />\n";
}
If Brazilian Portuguese language files aren’t available, then the Portuguese will be enabled instead: if Portuguese language files aren’t available, then the setLocale() method will return an error, and American English (en_us) settings will be used throughout.
More details of the features available once a locale has been set, including a list of the languages and locales currently supported, can be found in section REF _Ref259954895 \r \h 4.5.5 REF _Ref259954904 \h Locale Settings for Formulae.
## Clearing a Workbook from memory
The PHPExcel 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â€<C3A2>, 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â€<C3A2> these cyclic references before doing so. PHPExcel provides the disconnectWorksheets() method for this purpose.
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
## Worksheets
A worksheet is a collection of cells, formula’s, images, graphs, … It holds all data necessary to represent as 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 “WorkSheetâ€<C3A2> will be created containing the data from that file.
When you instantiate a new workbook, PHPExcel will create it with a single worksheet called “WorkSheetâ€<C3A2>.
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â€<C3A2> 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â€<C3A2> 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.
// Get the second sheet in the workbook
// Note that sheets are indexed from 0
$objPHPExcel->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.
// Retrieve the worksheet called 'Worksheet 1'
$objPHPExcel->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).
// Retrieve the current active worksheet
$objPHPExcel->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 PHPExcel object. By default, this will be created as a new “lastâ€<C3A2> 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.
$objPHPExcel->createSheet();
A new worksheet created using this method will be called “Worksheetâ€<C3A2> or “Worksheet<n>â€<EFBFBD> where “<n>â€<EFBFBD> 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.
// Create a new worksheet called “My Dataâ€<C3A2>
$myWorkSheet = new PHPExcel_Worksheet($objPHPExcel, 'My Data');
// Attach the “My Dataâ€<C3A2> worksheet as the first worksheet in the PHPExcel object
$objPHPExcel->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.
$objClonedWorksheet = clone $objPHPExcel->getSheetByName('Worksheet 1');
$objClonedWorksheet->setTitle('Copy of Worksheet 1')
$objPHPExcel->addSheet($objClonedWorksheet);
You can also copy worksheets from one workbook to another, though this is more complex as PHPExcel also has to replicate the styling between the two workbooks. The addExternalSheet() method is provided for this purpose.
$objClonedWorksheet = clone $objPHPExcel1->getSheetByName('Worksheet 1');
$objPHPExcel->addExternalSheet($objClonedWorksheet);
In both cases, it is the developer’s responsibility to ensure that worksheet names are not duplicated. PHPExcel 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
$sheetIndex = $objPHPExcel->getIndex($objPHPExcel-> getSheetByName('Worksheet 1'));
$objPHPExcel->removeSheetByIndex($sheetIndex);
If the currently active worksheet is deleted, then the sheet at the previous index position will become the currently active sheet.
## Accessing cells ## Accessing cells
Accessing cells in a PHPExcel worksheet should be pretty straightforward. This topic lists some of the options to access a cell. Accessing cells in a PHPExcel worksheet 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
Setting a cell value by coordinate can be done using the worksheet’s setCellValue method. Setting a cell value by coordinate can be done using the worksheet's `setCellValue()` method.
```php
// Set cell B8
$objPHPExcel->getActiveSheet()->setCellValue('B8', 'Some value'); $objPHPExcel->getActiveSheet()->setCellValue('B8', 'Some value');
```
Will set cell B8 in the currently active worksheet to a string value of "Some Value"
### Retrieving a cell by coordinate ### Retrieving a cell 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 again using the following line of code: To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the `getCell()` method. A cell's value can be read again using the following line of code:
```php
// Get cell B8
$objPHPExcel->getActiveSheet()->getCell('B8')->getValue(); $objPHPExcel->getActiveSheet()->getCell('B8')->getValue();
```
If you need the calculated value of a cell, use the following code. This is further explained in REF _Ref191885372 \w \h \* MERGEFORMAT 4.4.35. If a cell contains a formula, and you need to retrieve the calculated value rather than the formula itself, then use the following code. This is further explained in .
```php
// Get cell B8
$objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue(); $objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue();
```
### Setting a cell value by column and row ### Setting a cell value by column and row
Setting a cell value by coordinate can be done using the worksheets setCellValueByColumnAndRow method. Setting a cell value by coordinate can be done using the worksheets setCellValueByColumnAndRow method.
```php
// Set cell B8 // Set cell B8
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 8, 'Some value'); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 8, 'Some value');
```
### Retrieving a cell by column and row ### Retrieving a cell 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 cells value can be read again using the following line of code: To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the getCellByColumnAndRow method. A cells value can be read again using the following line of code:
```php
// Get cell B8 // Get cell B8
$objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getValue(); $objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getValue();
```
If you need the calculated value of a cell, use the following code. This is further explained in .
If you need the calculated value of a cell, use the following code. This is further explained in REF _Ref191885372 \w \h 4.4.35 ```php
// Get cell B8 // Get cell B8
$objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getCalculatedValue(); $objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getCalculatedValue();
```
### Looping cells ### Looping cells
@ -311,47 +63,32 @@ The easiest way to loop cells is by using iterators. Using iterators, one can us
Below is an example where we read all the values in a worksheet and display them in a table. Below is an example where we read all the values in a worksheet and display them in a table.
<?php ```php
$objReader = PHPExcel_IOFactory::createReader('Excel2007'); $objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true); $objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("test.xlsx"); $objPHPExcel = $objReader->load("test.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet(); $objWorksheet = $objPHPExcel->getActiveSheet();
echo '<table>' . "\n"; echo '<table>' . "\n";
foreach ($objWorksheet->getRowIterator() as $row) { foreach ($objWorksheet->getRowIterator() as $row) {
echo '<tr>' . "\n";
echo '<tr>' . "\n"; $cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops all cells,even if a cell is not set.
$cellIterator = $row->getCellIterator(); // By default, only cells that are set will be iterated.
foreach ($cellIterator as $cell) {
$cellIterator->setIterateOnlyExistingCells(false); // This loops all cells, echo '<td>' . $cell->getValue() . '</td>' . "\n";
// even if it is not set. }
// By default, only cells echo '</tr>' . "\n";
// that are set will be
// iterated.
foreach ($cellIterator as $cell) {
echo '<td>' . $cell->getValue() . '</td>' . "\n";
}
echo '</tr>' . "\n";
} }
echo '</table>' . "\n"; echo '</table>' . "\n";
?> ```
Note that we have set the cell iterator’s setIterateOnlyExistingCells() to false. This makes the iterator loop all cells, even if they were not set before. Note that we have set the cell iterator's `setIterateOnlyExistingCells()` to FALSE. This makes the iterator loop all cells, even if they were not set before.
__The cell iterator will return ____null____ as the cell if it is not set in the worksheet.__ __The cell iterator will return ____NULL____ as the cell 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. 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 cells using indexes #### Looping cells using indexes

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB