PHPExcel Developer Documentation
PHPExcel Developer Documentation
Contents
PHPExcel Developer Documentation.............................................................................1
1. Contents........................................................................................................ 2
2. Prerequisites................................................................................................... 5
2.1. Software requirements.................................................................................5
2.2. Installation instructions................................................................................5
2.3. Getting started.......................................................................................... 5
2.4. Useful links and tools...................................................................................5
2.4.1. OpenXML / SpreadsheetML......................................................................5
2.4.2. Frequently asked questions......................................................................6
2.4.3. Tutorials............................................................................................7
3. Architecture.................................................................................................... 8
3.1. Schematical..............................................................................................8
3.2. Lazy Loader..............................................................................................8
3.3. Spreadsheet in memory................................................................................8
3.4. Readers and writers.....................................................................................8
3.5. Fluent interfaces........................................................................................9
4. Creating a spreadsheet......................................................................................11
4.1. The PHPExcel class....................................................................................11
4.1.1. Loading a Workbook from a file...............................................................11
4.1.2. Creating a new workbook.......................................................................11
4.2. Configuration Settings................................................................................11
4.2.1. Cell Caching......................................................................................11
4.2.2. Language/Locale.................................................................................13
4.3. Clearing a Workbook from memory.................................................................14
4.4. Worksheets............................................................................................. 14
4.4.1. Adding a new Worksheet.......................................................................15
4.4.2. Copying Worksheets.............................................................................15
4.4.3. Removing a Worksheet..........................................................................15
4.5. Accessing cells......................................................................................... 16
4.5.1. Setting a cell value by coordinate.............................................................16
4.5.2. Setting a range of cells from an array........................................................18
4.5.3. Retrieving a cell by coordinate................................................................20
4.5.4. Setting a cell value by column and row......................................................20
4.5.5. Retrieving a cell by column and row..........................................................20
4.5.6. Looping cells......................................................................................21
4.5.7. Using value binders to facilitate data entry.................................................22
4.6. PHPExcel recipes.......................................................................................22
4.6.1. Setting a spreadsheet’s metadata.............................................................23
4.6.2. Setting a spreadsheet’s active sheet.........................................................23
4.6.3. Write a date or time into a cell...............................................................23
4.6.4. Write a formula into a cell.....................................................................24
4.6.5. Locale Settings for Formulae...................................................................25
4.6.6. Write a newline character "\n" in a cell (ALT+"Enter").....................................25
4.6.7. Explicitly set a cell’s datatype................................................................26
4.6.8. Change a cell into a clickable URL............................................................26
4.6.9. Setting a worksheet’s page orientation and size............................................26
4.6.10. Page Setup: Scaling options....................................................................26
4.6.11. Page margins.....................................................................................27
4.6.12. Center a page horizontally/vertically........................................................28
4.6.13. Setting the print header and footer of a worksheet........................................28
4.6.14. Setting printing breaks on a row or column..................................................30
4.6.15. Show/hide gridlines when printing............................................................30
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
...
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/ Examples/01simple.php
http://example.com/ Examples/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.
» Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 File Formats
http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-
The ZipArchive class is only required when reading or writing formats that use Zip compression
(Excel2007 and OOCalc). Since version 1.7.6 the PCLZip library has been bundled with PHPExcel as
an alternative to the ZipArchive class.
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
before calling the save method of the Excel2007 Writer.
PHPExcel_Settings::setZipClass(PHPExcel_Settings::ZIPARCHIVE);
At present, this only allows you to write Excel2007 files without the need for ZipArchive (not to
read Excel2007 or OOCalc)
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 should
work at all times.
If you can’t locate a clean copy of ZipArchive, then you can use the PCLZip library as an alternative
when writing Excel2007 files, as described above.
Fatal error: Allowed memory size of xxx bytes exhausted (tried to allocate yyy bytes)
in zzz on line aaa
PHPExcel holds an "in memory" representation of a spreadsheet, so it is restricted by 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 PHPExcel, on the discussion board.
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
For example autofilter is not implemented in PEAR Spreadsheet_Excel_writer, which is the base of
our Excel5 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.
The short answer is that PHPExcel uses a measure where padding is included. See section: “Setting
a column’s width” for more details.
2.4.3. 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
If your own scripts already define an autoload function, then this may be overwritten by the
PHPExcel autoload function. For example, if you have:
function __autoload($class) {
...
}
Do this instead:
function myAutoload($class) {
...
}
spl_autoload_register('myAutoload');
Just like desktop spreadsheet software, PHPExcel represents a spreadsheet containing one or more
worksheets, which contain cells with data, formulas, images, …
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->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");
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.
$inputFileName = './sampleData/example1.xls';
$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).
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 1 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
1
You must have APC enabled for PHP to use this option.
4.2.2. 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";
2
You must have a memcache server running, and have enabled memcache for your PHP to use this
option.
3
You must have Wincache enabled for PHP to use this option.
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 4.6.5 Locale Settings for Formulae.
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
4.4. 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” 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”.
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.
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.
You can change the currently active sheet by index or by name using the setActiveSheetIndex() and
setActiveSheetIndexByName()methods.
$objPHPExcel->createSheet();
A new worksheet created using this method will be called “Worksheet” or “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.
If you don’t specify an index position as the second argument, then the new worksheet will be
added after the last existing worksheet.
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.
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.
Alternatively, you can retrieve the cell object, and then call the cell’s setValue() method:
$objPHPExcel->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, PHPExcel 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 PHPExcel 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.
You can read more about value binders later in section 4.5.7 (“Using value binders to facilitate data
entry”) of this document.
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.
// 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
);
With number format masking, you can even break up the digits into groups to make the value
more easily readable.
// 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'
);
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).
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.
$arrayData = array(
array(NULL, 2010, 2011, 2012),
array('Q1', 12, 15, 21),
If you pass a 2-d array, then this will be treated as a series of rows and columns. A 1-d array
will be treated as a single row, which is particularly useful if you're fetching an array of data
from a database.
If you 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:
$objPHPExcel->getActiveSheet()->getCell('B8')->getValue();
If you need the calculated value of a cell, use the following code. This is further explained in
4.6.41.
$objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue();
// Set cell B8
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 8, 'Some value');
// Get cell B8
$objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getValue();
If you need the calculated value of a cell, use the following code. This is further explained in
section 4.6.41
// Get cell B8
$objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getCalculatedValue();
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();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // This loops all cells,
// even if it is not set.
// By default, only cells
// that are set will be
// iterated.
foreach ($cellIterator as $cell) {
echo '<td>' . $cell->getValue() . '</td>' . "\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.
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.
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();
Optionally, the default behaviour of PHPExcel can be modified, allowing easier data entry. For
example, a PHPExcel_Cell_AdvancedValueBinder class is present. It automatically converts
percentages 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:
/** PHPExcel */
require_once 'PHPExcel.php';
/** PHPExcel_Cell_AdvancedValueBinder */
require_once 'PHPExcel/Cell/AdvancedValueBinder.php';
/** PHPExcel_IOFactory */
require_once 'PHPExcel/IOFactory.php';
// ...
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX,
generated using PHP classes.");
$objPHPExcel->getProperties()->setKeywords("office 2007 openxml php");
$objPHPExcel->getProperties()->setCategory("Test result file");
$objPHPExcel->setActiveSheetIndex(0);
PHPExcel works with UST (Universal Standard Time) date and Time values, but does no internal
conversions; so it is up to the developer to ensure that values passed to the date/time conversion
functions are UST.
Writing a date value in a cell consists of 2 lines of code. Select the method that suits you the best.
Here are some examples:
The above methods for entering a date all yield the same result. PHPExcel_Style_NumberFormat
provides a lot of pre-defined date formats.
The PHPExcel_Shared_Date::PHPToExcel() method will also work with a PHP DateTime object.
Similarly, times (or date and time values) can be entered in the same fashion: just remember to use
an appropriate format code.
Notes:
1. See section "Using value binders to facilitate data entry" to learn more about the
AdvancedValueBinder used in the first example.
2. In previous versions of PHPExcel up to and including 1.6.6, when a cell had a date-like
number format code, it was possible to enter a date directly using an integer PHP-time
without converting to Excel date format. Starting with PHPExcel 1.6.7 this is no longer
supported.
3. 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 PHPExcel.
When the final workbook is opened by the user, Microsoft Office Excel will take care of displaying
the formula according the applications language. Translation is taken care of by the application!
The following line of code writes the formula “=IF(C4>500,"profit","loss")” into the cell B8. Note that
the formula must start with “=” to make PHPExcel recognise this as a formula.
$objPHPExcel->getActiveSheet()->setCellValue('B8','=IF(C4>500,"profit","loss")');
If you want to write a string beginning with an “=” to a cell, then you should use the
setCellValueExplicit() method.
$objPHPExcel->getActiveSheet()
->setCellValueExplicit('B8',
'=IF(C4>500,"profit","loss")',
PHPExcel_Cell_DataType::TYPE_STRING
);
A cell’s formula can be read again using the following line of code:
$formula = $objPHPExcel->getActiveSheet()->getCell('B8')->getValue();
$value = $objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue();
$locale = 'ru';
$validLocale = PHPExcel_Settings::setLocale($locale);
if (!$validLocale) {
echo 'Unable to set locale to '.$locale." - reverting to en_us<br />\n";
}
If Russian language files aren’t available, the setLocale() method will return an error, and English
settings will be used throughout.
Once you have set a locale, you can translate a formula from its internal English coding.
$formula = $objPHPExcel->getActiveSheet()->getCell('B8')->getValue();
$translatedFormula =
PHPExcel_Calculation::getInstance()->_translateFormulaToLocale($formula);
You can also create a formula using the function names and argument separators appropriate to the
defined locale; then translate it to English before setting the cell value:
$formula = '=ДНЕЙ360(ДАТА(2010;2;5);ДАТА(2010;12;31);ИСТИНА)';
$internalFormula =
PHPExcel_Calculation::getInstance()->translateFormulaToEnglish($formula);
$objPHPExcel->getActiveSheet()->setCellValue('B8',$internalFormula);
Currently, formula translation only translates the function names, the constants TRUE and FALSE,
and the function argument separators.
$objPHPExcel->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
Tip
Read more about formatting cells using getStyle() elsewhere.
Tip
AdvancedValuebinder.php automatically turns on "wrap text" for the cell when it sees a newline
character in a string that you are inserting in a cell. Just like Microsoft Office Excel. Try this:
require_once 'PHPExcel/Cell/AdvancedValueBinder.php';
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
$objPHPExcel->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
$objPHPExcel->getActiveSheet()->getCell('A1')->setValueExplicit('25',
PHPExcel_Cell_DataType::TYPE_NUMERIC);
$objPHPExcel->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
$objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()-
>setUrl('http://www.phpexcel.net');
If you want to make a hyperlink to another worksheet/cell, use the following code:
$objPHPExcel->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
$objPHPExcel->getActiveSheet()->getCell('E26')->getHyperlink()-
>setUrl(“sheet://'Sheetname'!A1”);
$objPHPExcel->getActiveSheet()->getPageSetup()-
>setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$objPHPExcel->getActiveSheet()->getPageSetup()-
>setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
Note that there are additional page settings available. Please refer to the API documentation for all
possible options.
Default values in PHPExcel correspond to default values in MS Office Excel as shown in illustration
Example
Here is how to fit to 1 page wide by infinite pages tall:
$objPHPExcel->getActiveSheet()->getPageSetup()->setFitToWidth(1);
$objPHPExcel->getActiveSheet()->getPageSetup()->setFitToHeight(0);
As you can see, it is not necessary to call setFitToPage(true) since setFitToWidth(…) and
setFitToHeight(…) triggers this.
If you use setFitToWidth() you should in general also specify setFitToHeight() explicitly like in
the example. Be careful relying on the initial values. This is especially true if you are upgrading from
PHPExcel 1.7.0 to 1.7.1 where the default values for fit-to-height and fit-to-width changed from 0 to 1.
$objPHPExcel->getActiveSheet()->getPageMargins()->setTop(1);
$objPHPExcel->getActiveSheet()->getPageMargins()->setRight(0.75);
$objPHPExcel->getActiveSheet()->getPageMargins()->setLeft(0.75);
$objPHPExcel->getActiveSheet()->getPageMargins()->setBottom(1);
$objPHPExcel->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);
$objPHPExcel->getActiveSheet()->getPageSetup()->setVerticalCentered(false);
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddHeader('&C&HPlease treat
this document as confidential!');
$objPHPExcel->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' .
$objPHPExcel->getProperties()->getTitle() . '&RPage &P of &N');
Substitution and formatting codes (starting with &) can be used inside headers and footers. There is
no required order in which these codes must appear.
The first occurrence of the following codes turns the formatting ON, the second occurrence turns it
OFF again:
» Strikethrough
» Superscript
» Subscript
Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the
other is ignored, while the first is ON.
&L Code for "left section" (there are three header / footer locations,
"left", "center", and "right"). When two or more occurrences of this
section marker exist, the contents from all markers are
concatenated, in the order of appearance, and placed into the left
section.
&P Code for "current page #"
&N Code for "total pages"
&font size Code for "text font size", where font size is a font size in points.
Tip
The above table of codes may seem overwhelming first time you are trying to figure out how to write some
header or footer. Luckily, there is an easier way. Let Microsoft Office Excel do the work for you.
For example, create in Microsoft Office Excel an xlsx file where you insert the header and footer as desired
using the programs own interface. Save file as test.xlsx. Now, take that file and read off the values using
PHPExcel as follows:
$objPHPexcel = PHPExcel_IOFactory::load('test.xlsx');
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.
$objPHPExcel->getActiveSheet()->setBreak( 'D10' ,
PHPExcel_Worksheet::BREAK_COLUMN );
$objPHPExcel->getActiveSheet()->setShowGridlines(true);
$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1,
5);
$objPHPExcel->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5');
$objPHPExcel->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5,G4:M20');
$objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->getColor()-
>setARGB(PHPExcel_Style_Color::COLOR_RED);
$objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()-
>setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
$objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getTop()-
>setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
$objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getBottom()-
>setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
$objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getLeft()-
>setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
$objPHPExcel->getActiveSheet()->getStyle('B2')->getFill()-
>setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$objPHPExcel->getActiveSheet()->getStyle('B2')->getFill()->getStartColor()-
>setARGB('FFFF0000');
Starting with PHPExcel 1.7.0 getStyle() also accepts a cell range as a parameter. For example, you
can set a red background color on a range of cells:
$objPHPExcel->getActiveSheet()->getStyle('B3:B7')->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');
Tip
It is recommended to style many cells at once, using e.g. getStyle('A1:M500'), rather than styling the cells
individually in a loop. This is much faster compared to looping through cells and styling them individually.
There is also an alternative manner to set styles. The following code sets a cell’s style to font bold,
alignment right, top border thin and a gradient fill:
$styleArray = array(
'font' => array(
'bold' => true,
),
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,
),
'borders' => array(
'top' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN,
),
),
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
'rotation' => 90,
'startcolor' => array(
'argb' => 'FFA0A0A0',
),
'endcolor' => array(
'argb' => 'FFFFFFFF',
),
),
);
$objPHPExcel->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B3:B7')->applyFromArray($styleArray);
This alternative method using arrays should be faster in terms of execution whenever you are
setting more than one style property. But the difference may barely be measurable unless you have
many different styles in your workbook.
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.
In Microsoft Office Excel you may be familiar with selecting a number format from the "Format
Cells" dialog. Here there are some predefined number formats available including some for dates.
The dialog is designed in a way so you don't have to interact with the underlying raw number format
code unless you need a custom number format.
In PHPExcel, you can also apply various predefined number formats. Example:
$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
This will format a number e.g. 1587.2 so it shows up as 1,587.20 when you open the workbook in MS
Office Excel. (Depending on settings for decimal and thousands separators in Microsoft Office Excel
it may show up as 1.587,20)
You can achieve exactly the same as the above by using this:
$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
->setFormatCode('#,##0.00');
In Microsoft Office Excel, as well as in PHPExcel, you will have to interact with raw number format
codes whenever you need some special custom number format. Example:
$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
->setFormatCode('[Blue][>=3000]$#,##0;[Red][<0]$#,##0;$#,##0');
Another example is when you want numbers zero-padded with leading zeros to a fixed length:
$objPHPExcel->getActiveSheet()->getCell('A1')->setValue(19);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
->setFormatCode('0000'); // will show as 0019 in Excel
Tip
The rules for composing a number format code in Excel can be rather complicated. Sometimes you know how
to create some number format in Microsoft Office Excel, but don't know what the underlying number format
code looks like. How do you find it?
The readers shipped with PHPExcel come to the rescue. Load your template workbook using e.g. Excel2007
reader to reveal the number format code. Example how read a number format code for cell A1:
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load('template.xlsx');
var_dump($objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()
->getFormatCode());
Advanced users may find it faster to inspect the number format code directly by renaming template.xlsx to
template.zip, unzipping, and looking for the relevant piece of XML code holding the number format code in
xl/styles.xml.
$objPHPExcel->getActiveSheet()->getStyle('A1:D4')
->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP);
$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');
$objPHPExcel->getDefaultStyle()->getFont()->setSize(8);
$styleArray = array(
'borders' => array(
'outline' => array(
'style' => PHPExcel_Style_Border::BORDER_THICK,
'color' => array('argb' => 'FFFF0000'),
),
),
);
$objWorksheet->getStyle('B2:G8')->applyFromArray($styleArray);
In Microsoft Office Excel, the above operation would correspond to selecting the cells B2:G8,
launching the style dialog, choosing a thick red border, and clicking on the "Outline" border
component.
Note that the border outline is applied to the rectangular selection B2:G8 as a whole, not on each cell
individually.
You can achieve any border effect by using just the 5 basic borders and operating on a single cell at
a time:
Additional shortcut borders come in handy like in the example above. These are the shortcut
borders available:
This border hierarchy can be utilized to achieve various effects in an easy manner.
One can set a conditional style ruleset to a cell using the following code:
$conditionalStyles = $objPHPExcel->getActiveSheet()->getStyle('B2')-
>getConditionalStyles();
array_push($conditionalStyles, $objConditional1);
array_push($conditionalStyles, $objConditional2);
$objPHPExcel->getActiveSheet()->getStyle('B2')-
>setConditionalStyles($conditionalStyles);
If you want to copy the ruleset to other cells, you can duplicate the style object:
$objPHPExcel->getActiveSheet()->duplicateStyle( $objPHPExcel->getActiveSheet()-
>getStyle('B2'), 'B3:B7' );
$objPHPExcel->getActiveSheet()->getComment('E11')->setAuthor('PHPExcel');
$objCommentRichText = $objPHPExcel->getActiveSheet()->getComment('E11')->getText()-
>createTextRun('PHPExcel:');
$objCommentRichText->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getComment('E11')->getText()->createTextRun("\r\n");
$objPHPExcel->getActiveSheet()->getComment('E11')->getText()->createTextRun('Total
amount on the current invoice, excluding VAT.');
$objPHPExcel->getActiveSheet()->setAutoFilter('A1:C9');
Make sure that you always include the complete filter range!
Excel does support setting only the caption row, but that's not a best practice...
$objPHPExcel->getSecurity()->setLockWindows(true);
$objPHPExcel->getSecurity()->setLockStructure(true);
$objPHPExcel->getSecurity()->setWorkbookPassword("PHPExcel");
$objPHPExcel->getActiveSheet()->getProtection()->setPassword('PHPExcel');
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
$objPHPExcel->getActiveSheet()->getProtection()->setSort(true);
$objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getProtection()->setLocked(
PHPExcel_Style_Protection::PROTECTION_UNPROTECTED
);
Make sure you enable worksheet protection if you need any of the worksheet protection features!
This can be done using the following code: $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
The following piece of code only allows numbers between 10 and 20 to be entered in cell B3:
$objValidation = $objPHPExcel->getActiveSheet()->getCell('B3')
->getDataValidation();
$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_WHOLE );
$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_STOP );
$objValidation->setAllowBlank(true);
$objValidation->setShowInputMessage(true);
$objValidation->setShowErrorMessage(true);
$objValidation->setErrorTitle('Input error');
$objValidation->setError('Number is not allowed!');
$objValidation->setPromptTitle('Allowed input');
$objValidation->setPrompt('Only numbers between 10 and 20 are allowed.');
$objValidation->setFormula1(10);
$objValidation->setFormula2(20);
The following piece of code only allows an item picked from a list of data to be entered in cell B3:
$objValidation = $objPHPExcel->getActiveSheet()->getCell('B5')
->getDataValidation();
$objValidation->setType( PHPExcel_Cell_DataValidation::TYPE_LIST );
$objValidation->setErrorStyle( PHPExcel_Cell_DataValidation::STYLE_INFORMATION );
$objValidation->setAllowBlank(false);
$objValidation->setShowInputMessage(true);
$objValidation->setShowErrorMessage(true);
$objValidation->setShowDropDown(true);
$objValidation->setErrorTitle('Input error');
$objValidation->setError('Value is not in list.');
$objValidation->setPromptTitle('Pick from list');
$objValidation->setPrompt('Please pick a value from the drop-down list.');
$objValidation->setFormula1('"Item A,Item B,Item C"');
When using a data validation list like above, make sure you put the list between " and " and that you
split the items with a comma (,).
It is important to remember that any string participating in an Excel formula is allowed to be
maximum 255 characters (not bytes). This sets a limit on how many items you can have in the string "Item
A,Item B,Item C". Therefore it is normally a better idea to type the item values directly in some cell range,
say A1:A3, and instead use, say, $objValidation->setFormula1('Sheet!$A$1:$A$3');. Another benefit is that the
item values themselves can contain the comma ‘,’ character itself.
If you need data validation on multiple cells, one can clone the ruleset:
$objPHPExcel->getActiveSheet()->getCell('B8')->setDataValidation(clone
$objValidation);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
If you want PHPExcel to perform an automatic width calculation, use the following code. PHPExcel
will approximate the column with to the width of the widest column value.
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
The measure for column width in PHPExcel 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.
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
PHPExcel and echo the retrieved values.
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setVisible(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setVisible(false);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1);
You can also collapse the column. Note that you should also set the column invisible, otherwise the
collapse will not be visible in Excel 2007.
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setCollapsed(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setVisible(false);
Please refer to the part “group/outline a row” for a complete example on collapsing.
You can instruct PHPExcel to add a summary to the right (default), or to the left. The following
code adds the summary to the left:
$objPHPExcel->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.
$objPHPExcel->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.
$objPHPExcel->getActiveSheet()->getRowDimension('5')->setOutlineLevel(1);
You can also collapse the row. Note that you should also set the row invisible, otherwise the
collapse will not be visible in Excel 2007.
$objPHPExcel->getActiveSheet()->getRowDimension('5')->setCollapsed(true);
$objPHPExcel->getActiveSheet()->getRowDimension('5')->setVisible(false);
$objPHPExcel->getActiveSheet()->getRowDimension($i)->setOutlineLevel(1);
$objPHPExcel->getActiveSheet()->getRowDimension($i)->setVisible(false);
}
$objPHPExcel->getActiveSheet()->getRowDimension(81)->setCollapsed(true);
You can instruct PHPExcel to add a summary below the collapsible rows (default), or above. The
following code adds the summary above:
$objPHPExcel->getActiveSheet()->setShowSummaryBelow(false);
$objPHPExcel->getActiveSheet()->mergeCells('A18:E22');
$objPHPExcel->getActiveSheet()->insertNewRowBefore(7, 2);
To add the above drawing to the worksheet, use the following snippet of code. PHPExcel creates
the link between the drawing and the worksheet:
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
You can set numerous properties on a drawing, here are some examples:
$objDrawing->setName('Paid');
$objDrawing->setDescription('Paid');
$objDrawing->setPath('./images/paid.png');
$objDrawing->setCoordinates('B15');
$objDrawing->setOffsetX(110);
$objDrawing->setRotation(25);
$objDrawing->getShadow()->setVisible(true);
$objDrawing->getShadow()->setDirection(45);
You can also add images created using GD functions without needing to save them to disk first as In-
Memory drawings.
$i = 0;
foreach ($objPHPExcel->getActiveSheet()->getDrawingCollection() as $drawing) {
if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
$extension = 'png'; break;
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif'; break;
case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg'; break;
}
} else {
$zipReader = fopen($drawing->getPath(),'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader,1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
}
$myFileName = '00_Image_'.++$i.'.'.$extension;
file_put_contents($myFileName,$imageContents);
}
This invoice is payable within thirty days after the end of the month unless specified otherwise
on the invoice.
$objPHPExcel->getActiveSheet()->getCell('A18')->setValue($objRichText);
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.
HTTP headers
Example of a script redirecting an Excel 2007 file to the client's browser:
<?php
/* Here there will be some code where you create $objPHPExcel */
<?php
/* Here there will be some code where you create $objPHPExcel */
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).
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).
$objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
Here’s an example which generates an image in memory and adds it to the active worksheet:
// Generate an image
$gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image
stream');
$textColor = imagecolorallocate($gdImage, 255, 255, 255);
imagestring($gdImage, 1, 5, 5, 'Created with PHPExcel', $textColor);
$objPHPExcel->getActiveSheet()->getSheetView()->setZoomScale(75);
$objWorksheet->getTabColor()->setRGB('FF0000');
$objWorksheet1 = $objPHPExcel->createSheet();
$objWorksheet1->setTitle('Another sheet');
$objPHPExcel->getActiveSheet()
->setSheetState(PHPExcel_Worksheet::SHEETSTATE_HIDDEN);
Sometimes you may even want the worksheet to be “very hidden”. The available sheet states are :
PHPExcel_Worksheet::SHEETSTATE_VISIBLE
PHPExcel_Worksheet::SHEETSTATE_HIDDEN
PHPExcel_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
$objPHPExcel->getActiveSheet()
->setRightToLeft(true);
To calculate a formula, you can call the cell containing the formula’s method
getCalculatedValue(), for example:
$objPHPExcel->getActiveSheet()->getCell('E11')->getCalculatedValue();
If you write the following line of code in the invoice demo included with PHPExcel, it evaluates to
the value "64":
Another nice feature of PHPExcel's formula parser, is that it can automatically adjust a formula
when inserting/removing rows/columns. Here's an example:
You see that the formula contained in cell E11 is "SUM(E4:E9)". Now, when I write the following line
of code, two new product lines are added:
$objPHPExcel->getActiveSheet()->insertNewRowBefore(7, 2);
6.1. PHPExcel_IOFactory
The PHPExcel API offers multiple methods to create a PHPExcel_Writer_IReader or
PHPExcel_Writer_IWriter instance:
Direct creation
Via PHPExcel_IOFactory
All examples underneath demonstrate the direct creation method. Note that you can also use the
PHPExcel_IOFactory class to do this.
Automatic file type resolving checks the different PHPExcel_Reader_IReader distributed with
PHPExcel. If one of them can load the specified file name, the file is loaded using that
PHPExcel_Reader_IReader. Explicit mode requires you to specify which PHPExcel_Reader_IReader
should be used.
$objPHPExcel = PHPExcel_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:
$objReader = PHPExcel_IOFactory::createReaderForFile("05featuredemo.xlsx");
$objReader->setReadDataOnly(true);
$objReader->load("05featuredemo.xlsx");
$objReader = PHPExcel_IOFactory::createReader("Excel2007");
$objPHPExcel = $objReader->load("05featuredemo.xlsx");
Note that automatic type resolving mode is slightly slower than explicit mode.
6.2.1. PHPExcel_Reader_Excel2007
Reading a spreadsheet
You can read an .xlsx file using the following code:
The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
return false;
}
}
6.2.2. PHPExcel_Writer_Excel2007
Writing a spreadsheet
You can write an .xlsx file using the following code:
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:
Excel5 file format will not be developed any further, it just provides an additional file format for
PHPExcel.
6.3.1. PHPExcel_Reader_Excel5
Reading a spreadsheet
You can read an .xls file using the following code:
The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
return false;
}
}
6.3.2. PHPExcel_Writer_Excel5
Writing a spreadsheet
You can write an .xls file using the following code:
6.4.1. PHPExcel_Reader_Excel2003XML
Reading a spreadsheet
You can read an .xml file using the following code:
The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
return false;
}
}
SYLK limitations
Please note that SYLK file format has some limits regarding to styling cells and handling large spreadsheets
via PHP.
6.5.1. PHPExcel_Reader_SYLK
Reading a spreadsheet
You can read an .slk file using the following code:
The following code will only read row 1 and rows 20 – 30 of any sheet in the SYLK file:
return false;
}
}
6.6.1. PHPExcel_Reader_OOCalc
Reading a spreadsheet
You can read an .ods file using the following code:
The following code will only read row 1 and rows 20 – 30 of any sheet in the Calc file:
return false;
}
}
CSV limitations
Please note that CSV file format has some limits regarding to styling cells, number formatting, …
6.7.1. PHPExcel_Reader_CSV
Reading a CSV file
You can read a .csv file using the following code:
$objReader->setSheetIndex(0);
6.7.2. PHPExcel_Writer_CSV
Writing a CSV file
You can write a .csv file using the following code:
$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:
By default PHPExcel 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:
require_once 'PHPExcel/Shared/String.php'
PHPExcel_Shared_String::setDecimalSeparator('.');
PHPExcel_Shared_String::setThousandsSeparator(',');
require_once 'PHPExcel/Shared/String.php'
PHPExcel_Shared_String::setDecimalSeparator(',');
PHPExcel_Shared_String::setThousandsSeparator('.');
Note that the above code sets decimal and thousand separators as global options. This also affects
how HTML and PDF is exported.
6.8. HTML
PHPExcel 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, …
6.8.1. PHPExcel_Reader_HTML
Reading a spreadsheet
You can read an .html or .htm file using the following code:
HTML limitations
Please note that HTML reader is still experimental and does not yet support merged cells or nested tables
cleanly
6.8.2. PHPExcel_Writer_HTML
Writing a spreadsheet
You can write a .htm file using the following code:
$objWriter->writeAllSheets();
$objWriter->setSheetIndex(0);
$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:
Supported methods:
generateHTMLHeader()
generateStyles()
generateSheetData()
generateHTMLFooter()
Here’s an example which retrieves all parts independently and merges them into a resulting HTML
page:
<?php
$objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
echo $objWriter->generateHTMLHeader();
?>
<?php
echo $objWriter->generateStyles(false); // do not write <style> and </style>
?>
-->
</style>
<?php
echo $objWriter->generateSheetData();
echo $objWriter->generateHTMLFooter();
?>
6.9. PDF
PHPExcel 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, …
6.9.1. PHPExcel_Writer_PDF
PHPExcel’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering library such as tcPDF, mPDF or
DomPDF. Prior to version 1.7.8 of PHPExcel, the tcPDF library was bundled with PHPExcel; but from
version 1.7.8 this was removed. Instead, you must now install a PDF Rendering library yourself; but
PHPExcel will work with a number of different libraries.
Currently, the following libraries are supported:
Version used
Library for testing Downloadable from PHPExcel 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.
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:
Please note that PHPExcel_Writer_PDF only outputs the first worksheet by default.
$objWriter->writeAllSheets();
$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:
Here is an example how to open a template file, fill in a couple of fields and save it again:
$objPHPexcel = PHPExcel_IOFactory::load('template.xlsx');
$objWorksheet = $objPHPexcel->getActiveSheet();
PHPExcel_Style
Array key: Maps to property:
fill getFill()
font getFont()
borders getBorders()
alignment getAlignment()
numberformat getNumberFormat()
protection getProtection()
quotePrefix setQuotePrefix()
PHPExcel_Style_Fill
Array key: Maps to property:
type setFillType()
rotation setRotation()
startcolor getStartColor()
endcolor getEndColor()
color getStartColor()
PHPExcel_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()
PHPExcel_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()
PHPExcel_Style_Border
Array key: Maps to property:
style setBorderStyle()
color getColor()
PHPExcel_Style_Alignment
Array key: Maps to property:
horizontal setHorizontal()
PHPExcel_Style_NumberFormat
Array key: Maps to property:
code setFormatCode()
PHPExcel_Style_Protection
Array key: Maps to property:
locked setLocked()
hidden setHidden()