PHP
PHP
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 "Tests" folder next to your "Classes" folder from above so you end up with:
/var/www/Tests/01simple.php
/var/www/Tests/02types.php
...
Start running the tests by pointing your browser to the test scripts:
http://example.com/Tests/01simple.php
http://example.com/Tests/02types.php
...
Note: It may be necessary to modify the include/require statements at the beginning of each of the test scripts if your
"Classes" folder from above is named differently.
» Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 File Formats
http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-
c6bb74cd1466&displaylang=en
Some versions of the 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.
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true);
For example autofilter is not implemented in PEAR Spreadsheet_Excel_writer, which is the base of
our Excel5 writer.
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
» French PHPExcel tutorial
http://g-ernaelsten.developpez.com/tutoriels/excel2007/
Just like desktop spreadsheet software, PHPExcel represents a spreadsheet containing one or more
worksheets, which contain cells with data, formulas, images, …
By default, the PHPExcel package provides some readers and writers, including one for the Open
XML spreadsheet format (a.k.a. Excel 2007 file format). You are not limited to the default readers
and writers, as you are free to implement the PHPExcel_Writer_IReader and
PHPExcel_Writer_IWriter interface in a custom class.
$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->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.
4.2. Worksheets
A worksheet is a collection of cells, formula’s, images, graphs, … It holds all data you want to
represent as a spreadsheet worksheet.
If you need the calculated value of a cell, use the following code. This is further explained in
4.4.36.
$objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue();
If you need the calculated value of a cell, use the following code. This is further explained in 4.4.36
// Get cell B8
$objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 8)->getCalculatedValue();
<?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';
// ...
For example, 4.4.7 Setting a worksheet’s page orientation and size covers setting a page orientation
to A4. Other paper formats, like US Letter, are not covered in this document, but in the PHPExcel
API documentation.
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:
// Excel-time
$objPHPExcel->getActiveSheet()->setCellValue('D1', 39813)
$objPHPExcel->getActiveSheet()->getStyle('D1')->getNumberFormat()-
>setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH)
The above methods for entering a date all yield the same result. PHPExcel_Style_NumberFormat
provides a lot of pre-defined date formats.
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.
Therefore, when you write formulas with PHPExcel, you must always use English formulas. The
following rules hold:
Decimal separator is '.' (period)
Function argument separator is ',' (comma)
Matrix row separator is ';' (semicolon)
Always use English function names
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")');
A cell’s formula can be read again using the following line of code:
$objPHPExcel->getActiveSheet()->getCell('B8')->getValue();
If you need the calculated value of a cell, use the following code. This is further explained in
4.4.36.
$objPHPExcel->getActiveSheet()->getCell('B8')->getCalculatedValue();
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”);
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.
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.
$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')->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.
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->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:
$objConditional1 = new PHPExcel_Style_Conditional();
$objConditional1->setConditionType(PHPExcel_Style_Conditional::CONDITION_CELLIS);
$objConditional1->setOperatorType(PHPExcel_Style_Conditional::OPERATOR_LESSTHAN);
$objConditional1->addCondition('0');
$objConditional1->getStyle()->getFont()->getColor()-
>setARGB(PHPExcel_Style_Color::COLOR_RED);
$objConditional1->getStyle()->getFont()->setBold(true);
$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' );
$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.');
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...
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);
$objPHPExcel->getActiveSheet()->getCell('B3')->setDataValidation($objValidation);
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"');
$objPHPExcel->getActiveSheet()->getCell('B5')->setDataValidation($objValidation);
When using a data validation list, make sure you put the list between “ and “ and that you split the
items with a comma (,).
If you need data validation on multiple cells, one can clone the ruleset:
$objPHPExcel->getActiveSheet()->getCell('B8')->setDataValidation(clone
$objValidation);
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);
PHPExcel always operates with 3) "Full width in character units" which is in fact the only value that is stored
in any Excel file, hence the most reliable measure. Unfortunately, Microsoft Office Excel does not present
you with this measure. Instead measures 1) and 2) are computed by the application when the file is opened
and these values are presented in various dialogues and tool tips.
The character width unit is the width of a '0' (zero) glyph in the workbooks default font. Therefore column
widths measured in character units in two different workbooks can only be compared if they have the same
default workbook font.
If you have some Excel file and need to know the column widths in measure 3), you can read the Excel file with
PHPExcel and echo the retrieved values.
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()->setShowSummaryRight(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);
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);
This invoice is payable within thirty days after the end of the month unless specified otherwise
on the invoice.
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).
Make sure that your script is saved without a BOM (Byte-order mark). (Because this counts
as echoing output)
Same things apply to all included files
Failing to follow the above guidelines may result in corrupt Excel files arriving at the client browser,
and/or that headers cannot be set by PHP (resulting in warning messages).
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);
$objWorksheet1 = $objPHPExcel->createSheet();
$objWorksheet1->setTitle('Another sheet');
Think of createSheet() as the "Insert sheet" button in Excel. When you hit that button a new sheet is appended
to the existing collection of worksheets in the workbook.
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.
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");
Note that automatic type resolving mode is slightly slower than explicit mode.
The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true;
}
return false;
}
}
6.2.2. PHPExcel_Writer_Excel2007
Writing a spreadsheet
You can write an .xlsx file using the following code:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save("05featuredemo.xlsx");
Formula pre-calculation
By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large
spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->setPreCalculateFormulas(false);
$objWriter->save("05featuredemo.xlsx");
6.3.1. PHPExcel_Reader_Serialized
Reading a spreadsheet
You can read a .phpxl file using the following code:
$objReader = new PHPExcel_Reader_Serialized();
$objPHPExcel = $objReader->load("05featuredemo.phpxl");
6.3.2. PHPExcel_Writer_Serialized
Writing a spreadsheet
You can write a .phpxl file using the following code:
$objWriter = new PHPExcel_Writer_Serialized($objPHPExcel);
$objWriter->save("05featuredemo.phpxl");
Excel5 file format will not be developed any further, it just provides an additional file format for
PHPExcel.
6.4.1. PHPExcel_Reader_Excel5
Reading a spreadsheet
You can read an .xls file using the following code:
$objReader = new PHPExcel_Reader_Excel5();
$objPHPExcel = $objReader->load("05featuredemo.xls");
The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true;
}
return false;
}
}
6.4.2. PHPExcel_Writer_Excel5
Writing a spreadsheet
You can write an .xls file using the following code:
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$objWriter->save("05featuredemo.xls");
6.5.1. PHPExcel_Reader_Excel2003XML
Reading a spreadsheet
You can read an .xml file using the following code:
$objReader = new PHPExcel_Reader_Excel2003XML();
$objPHPExcel = $objReader->load("05featuredemo.xml");
The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true;
}
return false;
}
}
6.6.1. PHPExcel_Reader_SYLK
Reading a spreadsheet
You can read an .slk file using the following code:
$objReader = new PHPExcel_Reader_SYLK();
$objPHPExcel = $objReader->load("05featuredemo.slk");
The following code will only read row 1 and rows 20 – 30 of any sheet in the SYLK file:
class MyReadFilter implements PHPExcel_Reader_IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Read title row and rows 20 - 30
if ($row == 1 || ($row >= 20 && $row <= 30)) {
return true;
}
return false;
}
}
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 = new PHPExcel_Reader_CSV();
$objPHPExcel = $objReader->load("sample.csv");
Note that PHPExcel_Reader_CSV by default assumes that the loaded CSV file is UTF-8 encoded. If
you are reading CSV files that were created in Microsoft Office Excel the correct input encoding may
rather be Windows-1252 (CP1252). Always make sure that the input encoding is set appropriately.
6.7.2. PHPExcel_Writer_CSV
Writing a CSV file
You can write a .csv file using the following code:
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
$objWriter->save("05featuredemo.csv");
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:
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
$objWriter->setPreCalculateFormulas(false);
$objWriter->save("05featuredemo.csv");
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(',');
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 write a spreadsheet into HTML format, for quick representation of the data
in it to anyone who does not have a spreadsheet application on their PC.
HTML limitations
Please note that HTML file format has some limits regarding to styling cells, number formatting, …
6.8.1. PHPExcel_Writer_HTML
Writing a spreadsheet
You can write a .htm file using the following code:
$objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
$objWriter->save("05featuredemo.htm");
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:
$objWriter = new PHPExcel_Writer_HTML($objPHPExcel);
$objWriter->setPreCalculateFormulas(false);
$objWriter->save("05featuredemo.htm");
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();
?>
<style>
<!--
html {
font-family: Times New Roman;
<?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
Please note that PHPExcel_Writer_PDF only outputs the first worksheet by default.
Writing a spreadsheet
You can write a .pdf file using the following code:
$objWriter = new PHPExcel_Writer_PDF($objPHPExcel);
$objWriter->save("05featuredemo.pdf");
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:
$objWriter = new PHPExcel_Writer_PDF($objPHPExcel);
$objWriter->setPreCalculateFormulas(false);
PHPExcel_Style
Array key: Maps to property:
fill getFill()
font getFont()
borders getBorders()
alignment getAlignment()
numberformat getNumberFormat()
protection getProtection()
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()
vertical setVertical()
PHPExcel_Style_NumberFormat
Array key: Maps to property:
code setFormatCode()
PHPExcel_Style_Protection
Array key: Maps to property:
locked setLocked()
hidden setHidden()