PhpSpreadsheet/docs/topics/recipes.md

1618 lines
56 KiB
Markdown
Raw Permalink Normal View History

# Recipes
2013-05-18 14:56:43 +00:00
The following pages offer you some widely-used PhpSpreadsheet recipes.
Please note that these do NOT offer complete documentation on specific
PhpSpreadsheet API functions, but just a bump to get you started. If you
need specific API functions, please refer to the [API documentation](https://phpoffice.github.io/PhpSpreadsheet).
2013-05-18 14:56:43 +00:00
For example, [setting a worksheet's page orientation and size
](#setting-a-worksheets-page-orientation-and-size) covers setting a page
orientation to A4. Other paper formats, like US Letter, are not covered
in this document, but in the PhpSpreadsheet [API documentation](https://phpoffice.github.io/PhpSpreadsheet).
2013-05-18 14:56:43 +00:00
## Setting a spreadsheet's metadata
2013-05-18 14:56:43 +00:00
PhpSpreadsheet allows an easy way to set a spreadsheet's metadata, using
document property accessors. Spreadsheet metadata can be useful for
finding a specific document in a file repository or a document
management system. For example Microsoft Sharepoint uses document
metadata to search for a specific document in its document lists.
2013-05-18 14:56:43 +00:00
Setting spreadsheet metadata is done as follows:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getProperties()
2013-05-18 14:56:43 +00:00
->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
2013-05-18 14:56:43 +00:00
->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");
```
## Setting a spreadsheet's active sheet
2013-05-18 14:56:43 +00:00
The following line of code sets the active sheet index to the first
sheet:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->setActiveSheetIndex(0);
2013-05-18 14:56:43 +00:00
```
You can also set the active sheet by its name/title
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->setActiveSheetIndexByName('DataSheet')
2013-05-18 14:56:43 +00:00
```
will change the currently active sheet to the worksheet called
"DataSheet".
2013-05-18 14:56:43 +00:00
## Write a date or time into a cell
2013-05-18 14:56:43 +00:00
In Excel, dates and Times are stored as numeric values counting the
number of days elapsed since 1900-01-01. For example, the date
'2008-12-31' is represented as 39813. You can verify this in Microsoft
Office Excel by entering that date in a cell and afterwards changing the
number format to 'General' so the true numeric value is revealed.
Likewise, '3:15 AM' is represented as 0.135417.
2013-05-18 14:56:43 +00:00
PhpSpreadsheet works with UST (Universal Standard Time) date and Time
values, but does no internal conversions; so it is up to the developer
to ensure that values passed to the date/time conversion functions are
UST.
2013-05-18 14:56:43 +00:00
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:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2013-05-18 14:56:43 +00:00
// MySQL-like timestamp '2008-12-31' or date string
\PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
2013-05-18 14:56:43 +00:00
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()
2013-05-18 14:56:43 +00:00
->setCellValue('D1', '2008-12-31');
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('D1')
2013-05-18 14:56:43 +00:00
->getNumberFormat()
2016-11-27 15:51:44 +00:00
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
2013-05-18 14:56:43 +00:00
// PHP-time (Unix time)
$time = gmmktime(0,0,0,12,31,2008); // int(1230681600)
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()
->setCellValue('D1', \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($time));
$spreadsheet->getActiveSheet()->getStyle('D1')
2013-05-18 14:56:43 +00:00
->getNumberFormat()
2016-11-27 15:51:44 +00:00
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
2013-05-18 14:56:43 +00:00
// Excel-date/time
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setCellValue('D1', 39813)
$spreadsheet->getActiveSheet()->getStyle('D1')
2013-05-18 14:56:43 +00:00
->getNumberFormat()
2016-11-27 15:51:44 +00:00
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
2013-05-18 14:56:43 +00:00
```
The above methods for entering a date all yield the same result.
2017-12-30 10:44:32 +00:00
`\PhpOffice\PhpSpreadsheet\Style\NumberFormat` provides a lot of
pre-defined date formats.
2013-05-18 14:56:43 +00:00
2017-12-30 10:44:32 +00:00
The `\PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel()` method will also
work with a PHP DateTime object.
2013-05-18 14:56:43 +00:00
Similarly, times (or date and time values) can be entered in the same
fashion: just remember to use an appropriate format code.
2013-05-18 14:56:43 +00:00
2018-01-04 04:34:25 +00:00
**Note:**
2013-05-18 14:56:43 +00:00
See section "Using value binders to facilitate data entry" to learn more
about the AdvancedValueBinder used in the first example. Excel can also
operate in a 1904-based calendar (default for workbooks saved on Mac).
Normally, you do not have to worry about this when using PhpSpreadsheet.
2015-04-08 16:27:14 +00:00
## Write a formula into a cell
2013-05-18 14:56:43 +00:00
Inside the Excel file, formulas are always stored as they would appear
in an English version of Microsoft Office Excel, and PhpSpreadsheet
handles all formulae internally in this format. This means that the
following rules hold:
2013-05-18 14:56:43 +00:00
- Decimal separator is `.` (period)
- Function argument separator is `,` (comma)
- Matrix row separator is `;` (semicolon)
- English function names must be used
2013-05-18 14:56:43 +00:00
This is regardless of which language version of Microsoft Office Excel
may have been used to create the Excel file.
2013-05-18 14:56:43 +00:00
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!
2013-05-18 14:56:43 +00:00
The following line of code writes the formula
`=IF(C4>500,"profit","loss")` into the cell B8. Note that the
formula must start with `=` to make PhpSpreadsheet recognise this as a
formula.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setCellValue('B8','=IF(C4>500,"profit","loss")');
2013-05-18 14:56:43 +00:00
```
If you want to write a string beginning with an `=` character to a
2017-03-13 05:57:37 +00:00
cell, then you should use the `setCellValueExplicit()` method.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()
2013-05-18 14:56:43 +00:00
->setCellValueExplicit(
'B8',
'=IF(C4>500,"profit","loss")',
2016-11-27 15:51:44 +00:00
\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING
2013-05-18 14:56:43 +00:00
);
```
A cell's formula can be read again using the following line of code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$formula = $spreadsheet->getActiveSheet()->getCell('B8')->getValue();
2013-05-18 14:56:43 +00:00
```
If you need the calculated value of a cell, use the following code. This
is further explained in [the calculation engine](./calculation-engine.md).
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$value = $spreadsheet->getActiveSheet()->getCell('B8')->getCalculatedValue();
2013-05-18 14:56:43 +00:00
```
## Locale Settings for Formulae
2013-05-18 14:56:43 +00:00
Some localisation elements have been included in PhpSpreadsheet. You can
set a locale by changing the settings. To set the locale to Russian you
would use:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2013-05-18 14:56:43 +00:00
$locale = 'ru';
2016-11-27 15:51:44 +00:00
$validLocale = \PhpOffice\PhpSpreadsheet\Settings::setLocale($locale);
2013-05-18 14:56:43 +00:00
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.
2013-05-18 14:56:43 +00:00
Once you have set a locale, you can translate a formula from its
internal English coding.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$formula = $spreadsheet->getActiveSheet()->getCell('B8')->getValue();
$translatedFormula = \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance()->_translateFormulaToLocale($formula);
2013-05-18 14:56:43 +00:00
```
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:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$formula = '=ДНЕЙ360(ДАТА(2010;2;5);ДАТА(2010;12;31);ИСТИНА)';
$internalFormula = \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance()->translateFormulaToEnglish($formula);
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setCellValue('B8',$internalFormula);
2013-05-18 14:56:43 +00:00
```
Currently, formula translation only translates the function names, the
constants TRUE and FALSE, and the function argument separators.
2013-05-18 14:56:43 +00:00
At present, the following locale settings are supported:
Language | | Locale Code
---------------------|----------------------|-------------
Czech | Ceština | cs
Danish | Dansk | da
German | Deutsch | de
Spanish | Español | es
Finnish | Suomi | fi
French | Français | fr
Hungarian | Magyar | hu
Italian | Italiano | it
Dutch | Nederlands | nl
Norwegian | Norsk | no
Polish | Jezyk polski | pl
Portuguese | Português | pt
Brazilian Portuguese | Português Brasileiro | pt_br
Russian | русский язык | ru
Swedish | Svenska | sv
Turkish | Türkçe | tr
## Write a newline character "\n" in a cell (ALT+"Enter")
2013-05-18 14:56:43 +00:00
In Microsoft Office Excel you get a line break in a cell by hitting
ALT+"Enter". When you do that, it automatically turns on "wrap text" for
the cell.
2013-05-18 14:56:43 +00:00
2016-11-27 15:51:44 +00:00
Here is how to achieve this in PhpSpreadsheet:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
$spreadsheet->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
2013-05-18 14:56:43 +00:00
```
**Tip**
2013-05-18 14:56:43 +00:00
2017-03-13 05:57:37 +00:00
Read more about formatting cells using `getStyle()` elsewhere.
2013-11-17 21:36:43 +00:00
**Tip**
2013-05-18 14:56:43 +00:00
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:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
\PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
2013-05-18 14:56:43 +00:00
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
2013-05-18 14:56:43 +00:00
```
Read more about AdvancedValueBinder.php elsewhere.
## Explicitly set a cell's datatype
2013-05-18 14:56:43 +00:00
You can set a cell's datatype explicitly by using the cell's
setValueExplicit method, or the setCellValueExplicit method of a
worksheet. Here's an example:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getCell('A1')
2013-05-18 14:56:43 +00:00
->setValueExplicit(
2016-11-27 15:51:44 +00:00
'25',
\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC
2013-05-18 14:56:43 +00:00
);
```
## Change a cell into a clickable URL
2013-05-18 14:56:43 +00:00
You can make a cell a clickable URL by setting its hyperlink property:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
2017-12-30 10:07:22 +00:00
$spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('https://www.example.com');
2013-05-18 14:56:43 +00:00
```
If you want to make a hyperlink to another worksheet/cell, use the
following code:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
$spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl("sheet://'Sheetname'!A1");
2013-05-18 14:56:43 +00:00
```
## Setting Printer Options for Excel files
2013-05-18 14:56:43 +00:00
### Setting a worksheet's page orientation and size
2013-05-18 14:56:43 +00:00
Setting a worksheet's page orientation and size can be done using the
following lines of code:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getPageSetup()
->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
$spreadsheet->getActiveSheet()->getPageSetup()
->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4);
2013-05-18 14:56:43 +00:00
```
Note that there are additional page settings available. Please refer to
the [API documentation](https://phpoffice.github.io/PhpSpreadsheet) for all possible options.
2013-05-18 14:56:43 +00:00
### Page Setup: Scaling options
2013-05-18 14:56:43 +00:00
The page setup scaling options in PhpSpreadsheet relate directly to the
scaling options in the "Page Setup" dialog as shown in the illustration.
2013-05-18 14:56:43 +00:00
Default values in PhpSpreadsheet correspond to default values in MS
Office Excel as shown in illustration
2013-05-18 14:56:43 +00:00
![08-page-setup-scaling-options.png](./images/08-page-setup-scaling-options.png)
2013-05-18 14:56:43 +00:00
method | initial value | calling method will trigger | Note
--------------------|:-------------:|-----------------------------|------
setFitToPage(...) | FALSE | - |
setScale(...) | 100 | setFitToPage(FALSE) |
setFitToWidth(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-width
setFitToHeight(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-height
2013-05-18 14:56:43 +00:00
#### Example
2013-05-18 14:56:43 +00:00
Here is how to fit to 1 page wide by infinite pages tall:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getPageSetup()->setFitToWidth(1);
$spreadsheet->getActiveSheet()->getPageSetup()->setFitToHeight(0);
2013-05-18 14:56:43 +00:00
```
As you can see, it is not necessary to call setFitToPage(TRUE) since
setFitToWidth(...) and setFitToHeight(...) triggers this.
2013-05-18 14:56:43 +00:00
2017-03-13 05:57:37 +00:00
If you use `setFitToWidth()` you should in general also specify
2017-12-30 10:44:32 +00:00
`setFitToHeight()` explicitly like in the example. Be careful relying on
the initial values.
2013-05-18 14:56:43 +00:00
### Page margins
2013-05-18 14:56:43 +00:00
To set page margins for a worksheet, use this code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getPageMargins()->setTop(1);
$spreadsheet->getActiveSheet()->getPageMargins()->setRight(0.75);
$spreadsheet->getActiveSheet()->getPageMargins()->setLeft(0.75);
$spreadsheet->getActiveSheet()->getPageMargins()->setBottom(1);
2013-05-18 14:56:43 +00:00
```
Note that the margin values are specified in inches.
![08-page-setup-margins.png](./images/08-page-setup-margins.png)
2013-05-18 14:56:43 +00:00
### Center a page horizontally/vertically
2013-05-18 14:56:43 +00:00
To center a page horizontally/vertically, you can use the following
code:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);
$spreadsheet->getActiveSheet()->getPageSetup()->setVerticalCentered(false);
2013-05-18 14:56:43 +00:00
```
### Setting the print header and footer of a worksheet
2013-05-18 14:56:43 +00:00
Setting a worksheet's print header and footer can be done using the
following lines of code:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getHeaderFooter()
2013-05-18 14:56:43 +00:00
->setOddHeader('&C&HPlease treat this document as confidential!');
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getHeaderFooter()
->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N');
2013-05-18 14:56:43 +00:00
```
Substitution and formatting codes (starting with &) can be used inside
headers and footers. There is no required order in which these codes
must appear.
2013-05-18 14:56:43 +00:00
The first occurrence of the following codes turns the formatting ON, the
second occurrence turns it OFF again:
2013-05-18 14:56:43 +00:00
- Strikethrough
- Superscript
- Subscript
2013-05-18 14:56:43 +00:00
Superscript and subscript cannot both be ON at same time. Whichever
comes first wins and the other is ignored, while the first is ON.
2013-05-18 14:56:43 +00:00
2016-10-06 11:39:10 +00:00
The following codes are supported by Xlsx:
2013-05-18 14:56:43 +00:00
Code | Meaning
-------------------------|-----------
`&L` | Code for "left section" (there are three header / footer locations, "left", "center", and "right"). When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the left section.
`&P` | Code for "current page #"
`&N` | Code for "total pages"
`&font size` | Code for "text font size", where font size is a font size in points.
`&K` | Code for "text font color" - RGB Color is specified as RRGGBB Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade value, NN is the tint/shade value.
`&S` | Code for "text strikethrough" on / off
`&X` | Code for "text super script" on / off
`&Y` | Code for "text subscript" on / off
`&C` | Code for "center section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the center section.
`&D` | Code for "date"
`&T` | Code for "time"
`&G` | Code for "picture as background" - Please make sure to add the image to the header/footer (see Tip for picture)
`&U` | Code for "text single underline"
`&E` | Code for "double underline"
`&R` | Code for "right section". When two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the order of appearance, and placed into the right section.
`&Z` | Code for "this workbook's file path"
`&F` | Code for "this workbook's file name"
`&A` | Code for "sheet tab name"
`&+` | Code for add to page #
`&-` | Code for subtract from page #
`&"font name,font type"` | Code for "text font name" and "text font type", where font name and font type are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font name, it means "none specified". Both of font name and font type can be localized values.
`&"-,Bold"` | Code for "bold font style"
`&B` | Code for "bold font style"
`&"-,Regular"` | Code for "regular font style"
`&"-,Italic"` | Code for "italic font style"
`&I` | Code for "italic font style"
`&"-,Bold Italic"` | Code for "bold italic font style"
`&O` | Code for "outline style"
`&H` | Code for "shadow style"
**Tip**
The above table of codes may seem overwhelming first time you are trying to
figure out how to write some header or footer. Luckily, there is an easier way.
Let Microsoft Office Excel do the work for you.For example, create in Microsoft
Office Excel an xlsx file where you insert the header and footer as desired
using the programs own interface. Save file as test.xlsx. Now, take that file
and read off the values using PhpSpreadsheet as follows:
2013-05-18 14:56:43 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('test.xlsx');
$worksheet = $spreadsheet->getActiveSheet();
2013-05-18 14:56:43 +00:00
var_dump($worksheet->getHeaderFooter()->getOddFooter());
var_dump($worksheet->getHeaderFooter()->getEvenFooter());
var_dump($worksheet->getHeaderFooter()->getOddHeader());
var_dump($worksheet->getHeaderFooter()->getEvenHeader());
2013-05-18 14:56:43 +00:00
```
That reveals the codes for the even/odd header and footer. Experienced
users may find it easier to rename test.xlsx to test.zip, unzip it, and
inspect directly the contents of the relevant xl/worksheets/sheetX.xml
to find the codes for header/footer.
**Tip for picture**
```php
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing();
$drawing->setName('PhpSpreadsheet logo');
$drawing->setPath('./images/PhpSpreadsheet_logo.png');
$drawing->setHeight(36);
$spreadsheet->getActiveSheet()->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT);
```
2013-05-18 14:56:43 +00:00
### Setting printing breaks on a row or column
2013-05-18 14:56:43 +00:00
To set a print break, use the following code, which sets a row break on
row 10.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$spreadsheet->getActiveSheet()->setBreak('A10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW);
2013-05-18 14:56:43 +00:00
```
The following line of code sets a print break on column D:
2020-05-31 13:41:05 +00:00
```php
$spreadsheet->getActiveSheet()->setBreak('D10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_COLUMN);
2013-05-18 14:56:43 +00:00
```
### Show/hide gridlines when printing
2013-05-18 14:56:43 +00:00
To show/hide gridlines when printing, use the following code:
2017-03-13 05:57:37 +00:00
```php
$spreadsheet->getActiveSheet()->setShowGridlines(true);
```
2013-05-18 14:56:43 +00:00
### Setting rows/columns to repeat at top/left
2013-05-18 14:56:43 +00:00
PhpSpreadsheet can repeat specific rows/cells at top/left of a page. The
following code is an example of how to repeat row 1 to 5 on each printed
page of a specific worksheet:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
2013-05-18 14:56:43 +00:00
```
### Specify printing area
2013-05-18 14:56:43 +00:00
To specify a worksheet's printing area, use the following code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5');
2013-05-18 14:56:43 +00:00
```
There can also be multiple printing areas in a single worksheet:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5,G4:M20');
2013-05-18 14:56:43 +00:00
```
## Styles
2013-05-18 14:56:43 +00:00
### Formatting cells
2013-05-18 14:56:43 +00:00
A cell can be formatted with font, border, fill, ... style information.
For example, one can set the foreground colour of a cell to red, aligned
to the right, and the border to black and thick border style. Let's do
that on cell B2:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('B2')
->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
$spreadsheet->getActiveSheet()->getStyle('B2')
->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
$spreadsheet->getActiveSheet()->getStyle('B2')
->getBorders()->getTop()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK);
$spreadsheet->getActiveSheet()->getStyle('B2')
->getBorders()->getBottom()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK);
$spreadsheet->getActiveSheet()->getStyle('B2')
->getBorders()->getLeft()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK);
$spreadsheet->getActiveSheet()->getStyle('B2')
->getBorders()->getRight()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK);
$spreadsheet->getActiveSheet()->getStyle('B2')
->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
$spreadsheet->getActiveSheet()->getStyle('B2')
2013-05-18 14:56:43 +00:00
->getFill()->getStartColor()->setARGB('FFFF0000');
```
`getStyle()` also accepts a cell range as a parameter. For example, you
can set a red background color on a range of cells:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('B3:B7')->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
2013-05-18 14:56:43 +00:00
->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.
2013-05-18 14:56:43 +00:00
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:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$styleArray = [
'font' => [
2013-05-18 14:56:43 +00:00
'bold' => true,
],
'alignment' => [
2016-11-27 15:51:44 +00:00
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT,
],
'borders' => [
'top' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
],
],
'fill' => [
'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR,
2013-05-18 14:56:43 +00:00
'rotation' => 90,
'startColor' => [
2013-05-18 14:56:43 +00:00
'argb' => 'FFA0A0A0',
],
'endColor' => [
2013-05-18 14:56:43 +00:00
'argb' => 'FFFFFFFF',
],
],
];
2013-05-18 14:56:43 +00:00
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray);
2013-05-18 14:56:43 +00:00
```
Or with a range of cells:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('B3:B7')->applyFromArray($styleArray);
2013-05-18 14:56:43 +00:00
```
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.
2013-05-18 14:56:43 +00:00
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
You can perform the opposite function, exporting a Style as an array,
as follows:
``` php
$styleArray = $spreadsheet->getActiveSheet()->getStyle('A3')->exportArray();
```
### Number formats
2013-05-18 14:56:43 +00:00
You often want to format numbers in Excel. For example you may want a
thousands separator plus a fixed number of decimals after the decimal
separator. Or perhaps you want some numbers to be zero-padded.
2013-05-18 14:56:43 +00:00
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.
2013-05-18 14:56:43 +00:00
In PhpSpreadsheet, you can also apply various predefined number formats.
Example:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()
->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
2013-05-18 14:56:43 +00:00
```
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)
2013-05-18 14:56:43 +00:00
You can achieve exactly the same as the above by using this:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()
2013-05-18 14:56:43 +00:00
->setFormatCode('#,##0.00');
```
In Microsoft Office Excel, as well as in PhpSpreadsheet, you will have
to interact with raw number format codes whenever you need some special
custom number format. Example:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()
2013-05-18 14:56:43 +00:00
->setFormatCode('[Blue][>=3000]$#,##0;[Red][<0]$#,##0;$#,##0');
```
Another example is when you want numbers zero-padded with leading zeros
to a fixed length:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getCell('A1')->setValue(19);
$spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()
2013-05-18 14:56:43 +00:00
->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?
2013-05-18 14:56:43 +00:00
The readers shipped with PhpSpreadsheet come to the rescue. Load your
template workbook using e.g. Xlsx reader to reveal the number format
code. Example how read a number format code for cell A1:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
$spreadsheet = $reader->load('template.xlsx');
2016-11-27 15:51:44 +00:00
var_dump($spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()->getFormatCode());
2013-05-18 14:56:43 +00:00
```
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*.
2013-05-18 14:56:43 +00:00
### Alignment and wrap text
2013-05-18 14:56:43 +00:00
Let's set vertical alignment to the top for cells A1:D4
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('A1:D4')
->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
2013-05-18 14:56:43 +00:00
```
Here is how to achieve wrap text:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('A1:D4')
2013-05-18 14:56:43 +00:00
->getAlignment()->setWrapText(true);
```
### Setting the default style of a workbook
2013-05-18 14:56:43 +00:00
It is possible to set the default style of a workbook. Let's set the
default font to Arial size 8:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getDefaultStyle()->getFont()->setName('Arial');
$spreadsheet->getDefaultStyle()->getFont()->setSize(8);
2013-05-18 14:56:43 +00:00
```
### Styling cell borders
2013-05-18 14:56:43 +00:00
In PhpSpreadsheet it is easy to apply various borders on a rectangular
selection. Here is how to apply a thick red border outline around cells
B2:G8.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$styleArray = [
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
'color' => ['argb' => 'FFFF0000'],
],
],
];
2013-05-18 14:56:43 +00:00
$worksheet->getStyle('B2:G8')->applyFromArray($styleArray);
2013-05-18 14:56:43 +00:00
```
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.
2013-05-18 14:56:43 +00:00
Note that the border outline is applied to the rectangular selection
B2:G8 as a whole, not on each cell individually.
2013-05-18 14:56:43 +00:00
You can achieve any border effect by using just the 5 basic borders and
operating on a single cell at a time:
2013-05-18 14:56:43 +00:00
- left
- right
- top
- bottom
- diagonal
2013-05-18 14:56:43 +00:00
Additional shortcut borders come in handy like in the example above.
These are the shortcut borders available:
2013-05-18 14:56:43 +00:00
- allBorders
- outline
- inside
- vertical
- horizontal
2013-05-18 14:56:43 +00:00
An overview of all border shortcuts can be seen in the following image:
![08-styling-border-options.png](./images/08-styling-border-options.png)
2013-05-18 14:56:43 +00:00
If you simultaneously set e.g. allBorders and vertical, then we have
"overlapping" borders, and one of the components has to win over the
other where there is border overlap. In PhpSpreadsheet, from weakest to
strongest borders, the list is as follows: allBorders, outline/inside,
vertical/horizontal, left/right/top/bottom/diagonal.
2013-05-18 14:56:43 +00:00
This border hierarchy can be utilized to achieve various effects in an
easy manner.
2013-05-18 14:56:43 +00:00
2017-03-13 05:57:37 +00:00
### Valid array keys for style `applyFromArray()`
The following table lists the valid array keys for
`\PhpOffice\PhpSpreadsheet\Style\Style::applyFromArray()` classes. If the "Maps
to property" column maps a key to a setter, the value provided for that
key will be applied directly. If the "Maps to property" column maps a
key to a getter, the value provided for that key will be applied as
another style array.
**\PhpOffice\PhpSpreadsheet\Style\Style**
Array key | Maps to property
-------------|-------------------
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
alignment | setAlignment()
borders | setBorders()
fill | setFill()
font | setFont()
numberFormat | setNumberFormat()
protection | setProtection()
quotePrefix | setQuotePrefix()
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
**\PhpOffice\PhpSpreadsheet\Style\Alignment**
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
Array key | Maps to property
------------|-------------------
horizontal | setHorizontal()
indent | setIndent()
readOrder | setReadOrder()
shrinkToFit | setShrinkToFit()
textRotation| setTextRotation()
vertical | setVertical()
wrapText | setWrapText()
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
**\PhpOffice\PhpSpreadsheet\Style\Border**
Array key | Maps to property
------------|-------------------
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
borderStyle | setBorderStyle()
color | setColor()
**\PhpOffice\PhpSpreadsheet\Style\Borders**
Array key | Maps to property
------------------|-------------------
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
allBorders | setLeft(); setRight(); setTop(); setBottom()
bottom | setBottom()
diagonal | setDiagonal()
diagonalDirection | setDiagonalDirection()
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
left | setLeft()
right | setRight()
top | setTop()
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
**\PhpOffice\PhpSpreadsheet\Style\Color**
Array key | Maps to property
------------|-------------------
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
argb | setARGB()
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
**\PhpOffice\PhpSpreadsheet\Style\Fill**
Array key | Maps to property
-----------|-------------------
color | getStartColor()
endColor | getEndColor()
fillType | setFillType()
rotation | setRotation()
startColor | getStartColor()
**\PhpOffice\PhpSpreadsheet\Style\Font**
Array key | Maps to property
------------|-------------------
Add exportArray Method for Styles (#1580) Issue #580 has gone stale since I started work on this. Nevertheless, this implements an exportArray function as an exact counterpart of applyFromArry. I chose the name exportArray to avoid confusion with the existing method getStyleArray, which does something completely different. This change also increases coverage for all the Style classes to 100%, with the exception of Style.php itself. There were several (unchanged) places in Style.php where I did not have sufficient understanding of what was supposed to be happening, so could not create tests. All properties used by applyFromArray are exported by this method. Note that conditional styles are not covered; this is consistent with the fact that they are not covered by applyFromArray. The method is implemented as a final public function in Style/Supervisor, which calls abstract protected function exportArray1, which is implemented in each of the subclasses, and which calls final protected function exportArray2 in Style/Supervisor. So exportArray is usable for any of the subclasses as well. The new method is added to the documentation. The existing documentation for applyFromArray was alphabetized to make it easier to follow. One property (Style quotePrefix) was added to the documentation. Some Borders pseudo-properties (vertical, horizontal, and outline) were documented as usable by applyFromArray, but aren't actually supported - they were removed. The documentation of the properties seemed to use setProperty and getProperty fairly randomly - it now uses setProperty exclusively. New constants were added for the textRotation "angles" used to create a "stacked" cell. I felt that changing the readers and writers to use these constants was beyond the scope of this change, but it is on my to-do list.
2020-10-26 19:56:24 +00:00
bold | setBold()
color | getColor()
italic | setItalic()
name | setName()
size | setSize()
strikethrough | setStrikethrough()
subscript | setSubscript()
superscript | setSuperscript()
underline | setUnderline()
**\PhpOffice\PhpSpreadsheet\Style\NumberFormat**
Array key | Maps to property
----------|-------------------
formatCode | setFormatCode()
**\PhpOffice\PhpSpreadsheet\Style\Protection**
Array key | Maps to property
----------|-------------------
locked | setLocked()
hidden | setHidden()
## Conditional formatting a cell
2013-05-18 14:56:43 +00:00
A cell can be formatted conditionally, based on a specific rule. For
example, one can set the foreground colour of a cell to red if its value
is below zero, and to green if its value is zero or more.
2013-05-18 14:56:43 +00:00
One can set a conditional style ruleset to a cell using the following
code:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$conditional1 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
$conditional1->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS);
$conditional1->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_LESSTHAN);
$conditional1->addCondition('0');
$conditional1->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
$conditional1->getStyle()->getFont()->setBold(true);
2013-05-18 14:56:43 +00:00
$conditional2 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
$conditional2->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS);
$conditional2->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_GREATERTHANOREQUAL);
$conditional2->addCondition('0');
$conditional2->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_GREEN);
$conditional2->getStyle()->getFont()->setBold(true);
2013-05-18 14:56:43 +00:00
2016-11-27 15:51:44 +00:00
$conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('B2')->getConditionalStyles();
$conditionalStyles[] = $conditional1;
$conditionalStyles[] = $conditional2;
2013-05-18 14:56:43 +00:00
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('B2')->setConditionalStyles($conditionalStyles);
2013-05-18 14:56:43 +00:00
```
If you want to copy the ruleset to other cells, you can duplicate the
style object:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()
2013-05-18 14:56:43 +00:00
->duplicateStyle(
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('B2'),
'B3:B7'
2013-05-18 14:56:43 +00:00
);
```
## Add a comment to a cell
2013-05-18 14:56:43 +00:00
To add a comment to a cell, use the following code. The example below
adds a comment to cell E11:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()
2013-05-18 14:56:43 +00:00
->getComment('E11')
->setAuthor('Mark Baker');
$commentRichText = $spreadsheet->getActiveSheet()
2013-05-18 14:56:43 +00:00
->getComment('E11')
2016-11-27 15:51:44 +00:00
->getText()->createTextRun('PhpSpreadsheet:');
$commentRichText->getFont()->setBold(true);
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()
2013-05-18 14:56:43 +00:00
->getComment('E11')
->getText()->createTextRun("\r\n");
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()
2013-05-18 14:56:43 +00:00
->getComment('E11')
->getText()->createTextRun('Total amount on the current invoice, excluding VAT.');
```
![08-cell-comment.png](./images/08-cell-comment.png)
2013-05-18 14:56:43 +00:00
## Apply autofilter to a range of cells
2013-05-18 14:56:43 +00:00
To apply an autofilter to a range of cells, use the following code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setAutoFilter('A1:C9');
2013-05-18 14:56:43 +00:00
```
**Make sure that you always include the complete filter range!** Excel
does support setting only the captionrow, but that's **not** a best
practice...
2013-05-18 14:56:43 +00:00
## Setting security on a spreadsheet
2013-05-18 14:56:43 +00:00
2017-09-08 18:16:47 +00:00
Excel offers 3 levels of "protection":
2013-05-18 14:56:43 +00:00
2017-09-08 18:16:47 +00:00
- Document: allows you to set a password on a complete
spreadsheet, allowing changes to be made only when that password is
2017-09-08 18:16:47 +00:00
entered.
- Worksheet: offers other security options: you can
disallow inserting rows on a specific sheet, disallow sorting, ...
- Cell: offers the option to lock/unlock a cell as well as show/hide
the internal formula.
**Make sure you enable worksheet protection if you need any of the
worksheet or cell protection features!** This can be done using the following
code:
2020-05-31 13:41:05 +00:00
```php
$spreadsheet->getActiveSheet()->getProtection()->setSheet(true);
```
### Document
2017-09-08 18:16:47 +00:00
An example on setting document security:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$security = $spreadsheet->getSecurity();
$security->setLockWindows(true);
$security->setLockStructure(true);
$security->setWorkbookPassword("PhpSpreadsheet");
2013-05-18 14:56:43 +00:00
```
### Worksheet
2013-05-18 14:56:43 +00:00
An example on setting worksheet security:
2020-05-31 13:41:05 +00:00
```php
$protection = $spreadsheet->getActiveSheet()->getProtection();
$protection->setPassword('PhpSpreadsheet');
$protection->setSheet(true);
$protection->setSort(true);
$protection->setInsertRows(true);
$protection->setFormatCells(true);
2013-05-18 14:56:43 +00:00
```
If writing Xlsx files you can specify the algorithm used to hash the password
before calling `setPassword()` like so:
```php
$protection = $spreadsheet->getActiveSheet()->getProtection();
$protection->setAlgorithm(Protection::ALGORITHM_SHA_512);
$protection->setSpinCount(20000);
$protection->setPassword('PhpSpreadsheet');
```
The salt should **not** be set manually and will be automatically generated
when setting a new password.
### Cell
2013-05-18 14:56:43 +00:00
An example on setting cell security:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getStyle('B1')
2013-05-18 14:56:43 +00:00
->getProtection()
2016-11-27 15:51:44 +00:00
->setLocked(\PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_UNPROTECTED);
```
## Reading protected spreadsheet
2013-05-18 14:56:43 +00:00
2020-06-03 00:13:29 +00:00
Spreadsheets that are protected as described above can always be read by
PhpSpreadsheet. There is no need to know the password or do anything special in
order to read a protected file.
However if you need to implement a password verification mechanism, you can use the
following helper method:
```php
$protection = $spreadsheet->getActiveSheet()->getProtection();
$allowed = $protection->verify('my password');
if ($allowed) {
doSomething();
} else {
throw new Exception('Incorrect password');
}
```
2013-05-18 14:56:43 +00:00
If you need to completely prevent reading a file by any tool, including PhpSpreadsheet,
then you are looking for "encryption", not "protection".
## Setting data validation on a cell
2013-05-18 14:56:43 +00:00
Data validation is a powerful feature of Xlsx. It allows to specify an
input filter on the data that can be inserted in a specific cell. This
filter can be a range (i.e. value must be between 0 and 10), a list
(i.e. value must be picked from a list), ...
2013-05-18 14:56:43 +00:00
The following piece of code only allows numbers between 10 and 20 to be
entered in cell B3:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$validation = $spreadsheet->getActiveSheet()->getCell('B3')
2013-05-18 14:56:43 +00:00
->getDataValidation();
$validation->setType( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_WHOLE );
$validation->setErrorStyle( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_STOP );
$validation->setAllowBlank(true);
$validation->setShowInputMessage(true);
$validation->setShowErrorMessage(true);
$validation->setErrorTitle('Input error');
$validation->setError('Number is not allowed!');
$validation->setPromptTitle('Allowed input');
$validation->setPrompt('Only numbers between 10 and 20 are allowed.');
$validation->setFormula1(10);
$validation->setFormula2(20);
2013-05-18 14:56:43 +00:00
```
The following piece of code only allows an item picked from a list of
data to be entered in cell B5:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$validation = $spreadsheet->getActiveSheet()->getCell('B5')
2013-05-18 14:56:43 +00:00
->getDataValidation();
$validation->setType( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_LIST );
$validation->setErrorStyle( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_INFORMATION );
$validation->setAllowBlank(false);
$validation->setShowInputMessage(true);
$validation->setShowErrorMessage(true);
$validation->setShowDropDown(true);
$validation->setErrorTitle('Input error');
$validation->setError('Value is not in list.');
$validation->setPromptTitle('Pick from list');
$validation->setPrompt('Please pick a value from the drop-down list.');
$validation->setFormula1('"Item A,Item B,Item C"');
2013-05-18 14:56:43 +00:00
```
When using a data validation list like above, make sure you put the list
2017-03-13 05:57:37 +00:00
between `"` and `"` and that you split the items with a comma (`,`).
2013-05-18 14:56:43 +00:00
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,
2017-03-13 05:57:37 +00:00
`$validation->setFormula1('Sheet!$A$1:$A$3')`. Another benefit is that
the item values themselves can contain the comma `,` character itself.
2013-05-18 14:56:43 +00:00
If you need data validation on multiple cells, one can clone the
ruleset:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$spreadsheet->getActiveSheet()->getCell('B8')->setDataValidation(clone $validation);
2013-05-18 14:56:43 +00:00
```
## Setting a column's width
2013-05-18 14:56:43 +00:00
A column's width can be set using the following code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(12);
2013-05-18 14:56:43 +00:00
```
If you want PhpSpreadsheet to perform an automatic width calculation,
use the following code. PhpSpreadsheet will approximate the column with
to the width of the widest column value.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
2013-05-18 14:56:43 +00:00
```
![08-column-width.png](./images/08-column-width.png)
The measure for column width in PhpSpreadsheet does **not** correspond
exactly to the measure you may be used to in Microsoft Office Excel.
Column widths are difficult to deal with in Excel, and there are several
2017-03-10 10:56:38 +00:00
measures for the column width.
1. Inner width in character units
(e.g. 8.43 this is probably what you are familiar with in Excel)
2. Full width in pixels (e.g. 64 pixels)
3. Full width in character units (e.g. 9.140625, value -1 indicates unset width)
**PhpSpreadsheet 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
2017-03-10 10:56:38 +00:00
with this measure**. Instead measures 1 and 2 are computed by the
application when the file is opened and these values are presented in
2017-03-10 10:56:38 +00:00
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
2017-03-10 10:56:38 +00:00
Excel file and need to know the column widths in measure 3, you can
read the Excel file with PhpSpreadsheet and echo the retrieved values.
2013-05-18 14:56:43 +00:00
## Show/hide a column
2013-05-18 14:56:43 +00:00
To set a worksheet's column visibility, you can use the following code.
The first line explicitly shows the column C, the second line hides
column D.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getColumnDimension('C')->setVisible(true);
$spreadsheet->getActiveSheet()->getColumnDimension('D')->setVisible(false);
2013-05-18 14:56:43 +00:00
```
## Group/outline a column
2013-05-18 14:56:43 +00:00
To group/outline a column, you can use the following code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1);
2013-05-18 14:56:43 +00:00
```
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.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getColumnDimension('E')->setCollapsed(true);
$spreadsheet->getActiveSheet()->getColumnDimension('E')->setVisible(false);
2013-05-18 14:56:43 +00:00
```
Please refer to the section "group/outline a row" for a complete example
on collapsing.
2013-05-18 14:56:43 +00:00
You can instruct PhpSpreadsheet to add a summary to the right (default),
or to the left. The following code adds the summary to the left:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setShowSummaryRight(false);
2013-05-18 14:56:43 +00:00
```
## Setting a row's height
2013-05-18 14:56:43 +00:00
A row's height can be set using the following code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getRowDimension('10')->setRowHeight(100);
2013-05-18 14:56:43 +00:00
```
Excel measures row height in points, where 1 pt is 1/72 of an inch (or
about 0.35mm). The default value is 12.75 pts; and the permitted range
of values is between 0 and 409 pts, where 0 pts is a hidden row.
## Show/hide a row
2013-05-18 14:56:43 +00:00
To set a worksheet''s row visibility, you can use the following code.
The following example hides row number 10.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getRowDimension('10')->setVisible(false);
2013-05-18 14:56:43 +00:00
```
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.
2013-05-18 14:56:43 +00:00
## Group/outline a row
2013-05-18 14:56:43 +00:00
To group/outline a row, you can use the following code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getRowDimension('5')->setOutlineLevel(1);
2013-05-18 14:56:43 +00:00
```
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.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getRowDimension('5')->setCollapsed(true);
$spreadsheet->getActiveSheet()->getRowDimension('5')->setVisible(false);
2013-05-18 14:56:43 +00:00
```
Here's an example which collapses rows 50 to 80:
2020-05-31 13:41:05 +00:00
```php
2013-05-18 14:56:43 +00:00
for ($i = 51; $i <= 80; $i++) {
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setCellValue('A' . $i, "FName $i");
$spreadsheet->getActiveSheet()->setCellValue('B' . $i, "LName $i");
$spreadsheet->getActiveSheet()->setCellValue('C' . $i, "PhoneNo $i");
$spreadsheet->getActiveSheet()->setCellValue('D' . $i, "FaxNo $i");
$spreadsheet->getActiveSheet()->setCellValue('E' . $i, true);
$spreadsheet->getActiveSheet()->getRowDimension($i)->setOutlineLevel(1);
$spreadsheet->getActiveSheet()->getRowDimension($i)->setVisible(false);
2013-05-18 14:56:43 +00:00
}
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getRowDimension(81)->setCollapsed(true);
2013-05-18 14:56:43 +00:00
```
You can instruct PhpSpreadsheet to add a summary below the collapsible
rows (default), or above. The following code adds the summary above:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->setShowSummaryBelow(false);
2013-05-18 14:56:43 +00:00
```
## Merge/unmerge cells
2013-05-18 14:56:43 +00:00
If you have a big piece of data you want to display in a worksheet, you
can merge two or more cells together, to become one cell. This can be
done using the following code:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->mergeCells('A18:E22');
2013-05-18 14:56:43 +00:00
```
Removing a merge can be done using the unmergeCells method:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->unmergeCells('A18:E22');
2013-05-18 14:56:43 +00:00
```
## Inserting rows/columns
2013-05-18 14:56:43 +00:00
You can insert/remove rows/columns at a specific position. The following
code inserts 2 new rows, right before row 7:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->insertNewRowBefore(7, 2);
2013-05-18 14:56:43 +00:00
```
## Add a drawing to a worksheet
2013-05-18 14:56:43 +00:00
A drawing is always represented as a separate object, which can be added
to a worksheet. Therefore, you must first instantiate a new
2017-12-30 10:44:32 +00:00
`\PhpOffice\PhpSpreadsheet\Worksheet\Drawing`, and assign its properties a
meaningful value:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('Logo');
$drawing->setDescription('Logo');
$drawing->setPath('./images/officelogo.jpg');
$drawing->setHeight(36);
2013-05-18 14:56:43 +00:00
```
To add the above drawing to the worksheet, use the following snippet of
code. PhpSpreadsheet creates the link between the drawing and the
worksheet:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$drawing->setWorksheet($spreadsheet->getActiveSheet());
2013-05-18 14:56:43 +00:00
```
You can set numerous properties on a drawing, here are some examples:
2020-05-31 13:41:05 +00:00
```php
$drawing->setName('Paid');
$drawing->setDescription('Paid');
$drawing->setPath('./images/paid.png');
$drawing->setCoordinates('B15');
$drawing->setOffsetX(110);
$drawing->setRotation(25);
$drawing->getShadow()->setVisible(true);
$drawing->getShadow()->setDirection(45);
2013-05-18 14:56:43 +00:00
```
You can also add images created using GD functions without needing to
save them to disk first as In-Memory drawings.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2013-05-18 14:56:43 +00:00
// Use GD to create an in-memory image
$gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream');
$textColor = imagecolorallocate($gdImage, 255, 255, 255);
2016-11-27 15:51:44 +00:00
imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor);
2013-05-18 14:56:43 +00:00
// Add the In-Memory image to a worksheet
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();
$drawing->setName('In-Memory image 1');
$drawing->setDescription('In-Memory image 1');
$drawing->setCoordinates('A1');
$drawing->setImageResource($gdImage);
$drawing->setRenderingFunction(
2016-11-27 15:51:44 +00:00
\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG
2013-05-18 14:56:43 +00:00
);
$drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT);
$drawing->setHeight(36);
$drawing->setWorksheet($spreadsheet->getActiveSheet());
2013-05-18 14:56:43 +00:00
```
## Reading Images from a worksheet
2013-05-18 14:56:43 +00:00
A commonly asked question is how to retrieve the images from a workbook
that has been loaded, and save them as individual image files to disk.
2013-05-18 14:56:43 +00:00
The following code extracts images from the current active worksheet,
and writes each as a separate file.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2013-05-18 14:56:43 +00:00
$i = 0;
2016-11-27 15:51:44 +00:00
foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) {
if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
2013-05-18 14:56:43 +00:00
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
2016-11-27 15:51:44 +00:00
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG :
$extension = 'png';
2013-05-18 14:56:43 +00:00
break;
2016-11-27 15:51:44 +00:00
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif';
2013-05-18 14:56:43 +00:00
break;
2016-11-27 15:51:44 +00:00
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg';
2013-05-18 14:56:43 +00:00
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);
}
```
## Add rich text to a cell
2013-05-18 14:56:43 +00:00
Adding rich text to a cell can be done using
`\PhpOffice\PhpSpreadsheet\RichText\RichText` instances. Here''s an example, which
creates the following rich text string:
2013-05-18 14:56:43 +00:00
> This invoice is ***payable within thirty days after the end of the
> month*** unless specified otherwise on the invoice.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$richText = new \PhpOffice\PhpSpreadsheet\RichText\RichText();
$richText->createText('This invoice is ');
$payable = $richText->createTextRun('payable within thirty days after the end of the month');
$payable->getFont()->setBold(true);
$payable->getFont()->setItalic(true);
$payable->getFont()->setColor( new \PhpOffice\PhpSpreadsheet\Style\Color( \PhpOffice\PhpSpreadsheet\Style\Color::COLOR_DARKGREEN ) );
$richText->createText(', unless specified otherwise on the invoice.');
$spreadsheet->getActiveSheet()->getCell('A18')->setValue($richText);
2013-05-18 14:56:43 +00:00
```
## Define a named range
2013-05-18 14:56:43 +00:00
PhpSpreadsheet supports the definition of named ranges. These can be
defined using the following code:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2013-05-18 14:56:43 +00:00
// Add some data
2016-11-27 15:51:44 +00:00
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname:');
$spreadsheet->getActiveSheet()->setCellValue('A2', 'Lastname:');
$spreadsheet->getActiveSheet()->setCellValue('B1', 'Maarten');
$spreadsheet->getActiveSheet()->setCellValue('B2', 'Balliauw');
2013-05-18 14:56:43 +00:00
// Define named ranges
Named formula implementation, and improved handling of Defined Names generally (#1535) * Initial work modifying the way named ranges are stored, and handled by the calculation engine This should provide better support for: - both union and intersection operators in composite named range values - MS Excel implementation of the union operator duplicating values - named formulae - named ranges and formulae that reference other named ranges and formulae - ranges and formulae that reference multiple ranges across multiple worksheets * Initial work on handling defined names (named ranges and named formulae) correctly - UTF-8 names (already extracted as a separate PR and merged) - distinction between named ranges and named formulae - correct handling of union and intersection operators in named ranges - correct evaluation of named range operators in calculations - calculation support for named formulae - support for nested ranges and formulae (named ranges and formulae that reference other named ranges/formulae) in calculations * Minor tweaks before resolving merge conflicts * Fix extractSheetTitle() method to work on the last ! in a cell reference rather than the first * Throw exception if a the reference to a defined name in a formula doesn't exist as a defined name * Properly assess scope for defined names in calculation engine * Elimination of some redundant code * Minor tweaks to simplify entries o the stack where we need to check type * Ensure correct scoping rules are applied when evaluating named ranges and formulae * Adjustments to Gnumeric Reader for new defined names structure * Initial work modifying the Ods Reader to handle named ranges, they weren't actually supported previously... this is still ongoing work * Handle Ranges formatted as 3-d ranges, as long as the references are both to the same worksheet * Additional testing for Named Ranges formatted as 3-d ranges, as long as the references are both to the same worksheet * Skip composite named range tests for the moment * Clean handling for `undefined name` exception when thrown in the calculation engine. Catch and replace with `#NAME?` * Adjust method we use to determine whether a defined name is a range or a formula * PHPCS Recommendations * PHP doesn't support `mixed` yet, at least not at the minium version that we're working with * More phpcs fixes * More phpcs appeasements * Final phpcs fixes for the moment Still have a lot of echo and var_dump() statements in the code that scrutinizer will hate, but they stay for the moment while this is still WIP * Please let this be the last of the phpcs fixes * Unit tests to determine whether a defined name value is a range value or a formula * phpcs appeasement * Named tests from provider * Initial steps for named ranges and formulae in the Ods Reader * Reading pseudo-3d range addresses in Ods; treat second sheet reference as being identical to the first, which is the majority of cases where this will occur * Initial work on Gnumeric reader for named ranges and formulae * Suppress debug logging again * Remove more debugging displays * Last minor tweaks before phase two * Minor refinements * And all for the want of a space * A little tidying up * More tidying up * phpcs fix * Modify defined names in rebindParent() * Renaming variables * Resolve an issue with locally scoped defined names that don't contain any worksheet reference * Keep phpcs happy * Fix quote handling in regexp * Fix a couple of scrutinizer issues * Fix a couple of scrutinizer issues * Update Xlsx Writer to work with the new defined name internal definition Additional validation checks * When adding new defined names through the readers, worksheet may not exist if we're only loading selected sheets rather than the full spreadsheet * If the only thing that phpcs can pickup on is strings in double quotes instead of single quotes, then I know I'm getting close to ready * Refactor Defined Names logic for Xlsx Writer into its own class * phpcs keeping me on my toes * Restore a couple of files that I managed to change without intending to * Initial work on Ods Write to provide support for saving named ranges and formulae * Resolve commas to semi-colons s argument separator when writing named formulae for Ods * Extract Named Expression Writer for Ods into its own class * Keep phpcs happy * Refactoring of formula conversion when reading SpreadsheetML; preparation for reading named ranges because they will also need to use the same conversion method * First pass at reading Named Ranges/Formulae from SpreadsheetML format xml files * Remove unused namespace reference * Defined names being written correctly for Xls; but not yet writing cell formulae that reference those defined names... that's the next big step And I anticipate that defined names that reference other defined names will also be a problem * Just to keep phpcs happy ... and yes, I know that there are still diagnostic echo statements in the code * I had to miss some of the phpcs issues didn't I * Work on the Xls Writer's Parser Tree to identify named range tokens in a formula, and to distinguish them from function tokens * Still working on packing that d*** defined name reference in the writer * Throw an exception in the Parser for saving Xls output if we encounter a defined name in a formula... writer will simply write the calculated cell value, and not the formula as at present Strip out diagnostic output * Some phpcs appeasement * Fix a couple of Scrutinizer issues * Additional verifications to differentiate a formula from a range value Add explicit getters/setters for named ranges, named formulae and defined names Additional unit tests * Styling for closures * Remove redundant docblocks * Spaces * Gah! Namespace use complaints * Consistency of making calls to DefinedName rather than NamedRange; NamedRange should now be used only for Named Ranges, and should exclude Named Formulae * Styling * spurious newline * No need to test for variable === null when we're typing it in the function argument definition * Additional unit tests for local/global scoped named ranges and formulae; and a fix to getNamedFormula() * Fix silly typo that led to breaking test * Void return signature for unit tests * Why weren't these picked up in the last pass? * Refactoring of getNamedRange()/getNamedFormula() * Eliminate unused constants, and defaults for private method parameters when always called with a value * Use strict comparisons when comparing object hash codes * Initial update to documentation for working with named formulae * Fix for calculation of relative cell references in named ranges/formulae * Fix current named range tests, because we should be using absolute references; tests for relative named ranges to be added later * Fix for calculation of relative cell references in named ranges/formulae * Updates to changelog and documentation for handling of absolute/relative references in named ranges * Fix last remaining unit test with a named range reference * Refactor formula conversion for Ods into a separate class; I hadn't realised that it previously wrote formulae as the MS Excel syntax without any conversion to Ods format * Fix Ods Writer test xml to reflect Ods-native format for formula * Docblocks * Drop dollar prefix from Ods formulae and ranges unless it's necessary * Set the formula convertor in the content writer constructor * Documentation update * Minor updates * Remove var_dumps from file * Fix the spurious single quote that was breaking named expressions in the Ods Writer... big sigh of relief that I finally spotted it * Starting work on documentation for Defined Names, and some examples of using Named Ranges and Formulae * Starting work on documentation for Defined Names, and some examples of using Named Ranges and Formulae * Example of a relative named range for the documentation * Mustn't have phpcs problems in sample code either * More updates to the documentation * That should conclude the documentation for Named Ranges, now time to move on to documenting Named Formulae * That should conclude the documentation for Named Ranges, now time to move on to documenting Named Formulae * PHPCS appeasement in sample code * Initial documentation on Named Formulae * PHPCS appeasements * Additional comments in the documentation, and modify the named range name validation to support a \ as the first character in a name * Fix breaking build * Make defined names case-insensitive * Fix case-insensitivity * Improved documentation, and additional unit tests * Additional unit tests, and a fix for removing a globally scoped defined name even if a worksheet is specified in the method call * Fix unit test for removing named formulae * Use assertCount instead of assertSame * Forgotten voids * Fix arguments for assertCount * Unit tests for removing defined names, and a fix for removing locally scoped names * Unit tests for absolute and relative named ranges in calculation engine, and fix an issue with worksheet name in the offset adjustments for relative references * PHPCS Appeasement * Additional unit tests, more documentation, and a fix to the calculation engine when no worksheet reference is provided with a named formula * PHPCS appeasements * Additional documentation and examples of using Named Formulae * Additional examples to go with documentation * A few minor phpcs appeasements * Minor refactor of updateFormulaReferencesAnyWorksheet() method * Discard an unused method argument * Additional unit tests * Additional unit tests * Remove unused argument * Stricter typing * Fix return typehinting from remove named range/formula; should return the Spreadsheet object * Use return typehint of self rather than explicit object type * Redundant code just to keep scrutinizer happy * Minor change to handle merge conflict * phpcs fixes after merge * Namespace usage ordering * Please let this be the last phpcs fix needed Co-authored-by: Adrien Crivelli <adrien.crivelli@gmail.com>
2020-07-26 10:00:06 +00:00
$spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonFN', $spreadsheet->getActiveSheet(), '$B$1'));
$spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonLN', $spreadsheet->getActiveSheet(), '$B$2'));
2013-05-18 14:56:43 +00:00
```
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.
2013-05-18 14:56:43 +00:00
Named formula implementation, and improved handling of Defined Names generally (#1535) * Initial work modifying the way named ranges are stored, and handled by the calculation engine This should provide better support for: - both union and intersection operators in composite named range values - MS Excel implementation of the union operator duplicating values - named formulae - named ranges and formulae that reference other named ranges and formulae - ranges and formulae that reference multiple ranges across multiple worksheets * Initial work on handling defined names (named ranges and named formulae) correctly - UTF-8 names (already extracted as a separate PR and merged) - distinction between named ranges and named formulae - correct handling of union and intersection operators in named ranges - correct evaluation of named range operators in calculations - calculation support for named formulae - support for nested ranges and formulae (named ranges and formulae that reference other named ranges/formulae) in calculations * Minor tweaks before resolving merge conflicts * Fix extractSheetTitle() method to work on the last ! in a cell reference rather than the first * Throw exception if a the reference to a defined name in a formula doesn't exist as a defined name * Properly assess scope for defined names in calculation engine * Elimination of some redundant code * Minor tweaks to simplify entries o the stack where we need to check type * Ensure correct scoping rules are applied when evaluating named ranges and formulae * Adjustments to Gnumeric Reader for new defined names structure * Initial work modifying the Ods Reader to handle named ranges, they weren't actually supported previously... this is still ongoing work * Handle Ranges formatted as 3-d ranges, as long as the references are both to the same worksheet * Additional testing for Named Ranges formatted as 3-d ranges, as long as the references are both to the same worksheet * Skip composite named range tests for the moment * Clean handling for `undefined name` exception when thrown in the calculation engine. Catch and replace with `#NAME?` * Adjust method we use to determine whether a defined name is a range or a formula * PHPCS Recommendations * PHP doesn't support `mixed` yet, at least not at the minium version that we're working with * More phpcs fixes * More phpcs appeasements * Final phpcs fixes for the moment Still have a lot of echo and var_dump() statements in the code that scrutinizer will hate, but they stay for the moment while this is still WIP * Please let this be the last of the phpcs fixes * Unit tests to determine whether a defined name value is a range value or a formula * phpcs appeasement * Named tests from provider * Initial steps for named ranges and formulae in the Ods Reader * Reading pseudo-3d range addresses in Ods; treat second sheet reference as being identical to the first, which is the majority of cases where this will occur * Initial work on Gnumeric reader for named ranges and formulae * Suppress debug logging again * Remove more debugging displays * Last minor tweaks before phase two * Minor refinements * And all for the want of a space * A little tidying up * More tidying up * phpcs fix * Modify defined names in rebindParent() * Renaming variables * Resolve an issue with locally scoped defined names that don't contain any worksheet reference * Keep phpcs happy * Fix quote handling in regexp * Fix a couple of scrutinizer issues * Fix a couple of scrutinizer issues * Update Xlsx Writer to work with the new defined name internal definition Additional validation checks * When adding new defined names through the readers, worksheet may not exist if we're only loading selected sheets rather than the full spreadsheet * If the only thing that phpcs can pickup on is strings in double quotes instead of single quotes, then I know I'm getting close to ready * Refactor Defined Names logic for Xlsx Writer into its own class * phpcs keeping me on my toes * Restore a couple of files that I managed to change without intending to * Initial work on Ods Write to provide support for saving named ranges and formulae * Resolve commas to semi-colons s argument separator when writing named formulae for Ods * Extract Named Expression Writer for Ods into its own class * Keep phpcs happy * Refactoring of formula conversion when reading SpreadsheetML; preparation for reading named ranges because they will also need to use the same conversion method * First pass at reading Named Ranges/Formulae from SpreadsheetML format xml files * Remove unused namespace reference * Defined names being written correctly for Xls; but not yet writing cell formulae that reference those defined names... that's the next big step And I anticipate that defined names that reference other defined names will also be a problem * Just to keep phpcs happy ... and yes, I know that there are still diagnostic echo statements in the code * I had to miss some of the phpcs issues didn't I * Work on the Xls Writer's Parser Tree to identify named range tokens in a formula, and to distinguish them from function tokens * Still working on packing that d*** defined name reference in the writer * Throw an exception in the Parser for saving Xls output if we encounter a defined name in a formula... writer will simply write the calculated cell value, and not the formula as at present Strip out diagnostic output * Some phpcs appeasement * Fix a couple of Scrutinizer issues * Additional verifications to differentiate a formula from a range value Add explicit getters/setters for named ranges, named formulae and defined names Additional unit tests * Styling for closures * Remove redundant docblocks * Spaces * Gah! Namespace use complaints * Consistency of making calls to DefinedName rather than NamedRange; NamedRange should now be used only for Named Ranges, and should exclude Named Formulae * Styling * spurious newline * No need to test for variable === null when we're typing it in the function argument definition * Additional unit tests for local/global scoped named ranges and formulae; and a fix to getNamedFormula() * Fix silly typo that led to breaking test * Void return signature for unit tests * Why weren't these picked up in the last pass? * Refactoring of getNamedRange()/getNamedFormula() * Eliminate unused constants, and defaults for private method parameters when always called with a value * Use strict comparisons when comparing object hash codes * Initial update to documentation for working with named formulae * Fix for calculation of relative cell references in named ranges/formulae * Fix current named range tests, because we should be using absolute references; tests for relative named ranges to be added later * Fix for calculation of relative cell references in named ranges/formulae * Updates to changelog and documentation for handling of absolute/relative references in named ranges * Fix last remaining unit test with a named range reference * Refactor formula conversion for Ods into a separate class; I hadn't realised that it previously wrote formulae as the MS Excel syntax without any conversion to Ods format * Fix Ods Writer test xml to reflect Ods-native format for formula * Docblocks * Drop dollar prefix from Ods formulae and ranges unless it's necessary * Set the formula convertor in the content writer constructor * Documentation update * Minor updates * Remove var_dumps from file * Fix the spurious single quote that was breaking named expressions in the Ods Writer... big sigh of relief that I finally spotted it * Starting work on documentation for Defined Names, and some examples of using Named Ranges and Formulae * Starting work on documentation for Defined Names, and some examples of using Named Ranges and Formulae * Example of a relative named range for the documentation * Mustn't have phpcs problems in sample code either * More updates to the documentation * That should conclude the documentation for Named Ranges, now time to move on to documenting Named Formulae * That should conclude the documentation for Named Ranges, now time to move on to documenting Named Formulae * PHPCS appeasement in sample code * Initial documentation on Named Formulae * PHPCS appeasements * Additional comments in the documentation, and modify the named range name validation to support a \ as the first character in a name * Fix breaking build * Make defined names case-insensitive * Fix case-insensitivity * Improved documentation, and additional unit tests * Additional unit tests, and a fix for removing a globally scoped defined name even if a worksheet is specified in the method call * Fix unit test for removing named formulae * Use assertCount instead of assertSame * Forgotten voids * Fix arguments for assertCount * Unit tests for removing defined names, and a fix for removing locally scoped names * Unit tests for absolute and relative named ranges in calculation engine, and fix an issue with worksheet name in the offset adjustments for relative references * PHPCS Appeasement * Additional unit tests, more documentation, and a fix to the calculation engine when no worksheet reference is provided with a named formula * PHPCS appeasements * Additional documentation and examples of using Named Formulae * Additional examples to go with documentation * A few minor phpcs appeasements * Minor refactor of updateFormulaReferencesAnyWorksheet() method * Discard an unused method argument * Additional unit tests * Additional unit tests * Remove unused argument * Stricter typing * Fix return typehinting from remove named range/formula; should return the Spreadsheet object * Use return typehint of self rather than explicit object type * Redundant code just to keep scrutinizer happy * Minor change to handle merge conflict * phpcs fixes after merge * Namespace usage ordering * Please let this be the last phpcs fix needed Co-authored-by: Adrien Crivelli <adrien.crivelli@gmail.com>
2020-07-26 10:00:06 +00:00
## Define a named formula
In addition to named ranges, PhpSpreadsheet also supports the definition of named formulae. These can be
defined using the following code:
```php
// Add some data
$spreadsheet->setActiveSheetIndex(0);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet
->setCellValue('A1', 'Product')
->setCellValue('B1', 'Quantity')
->setCellValue('C1', 'Unit Price')
->setCellValue('D1', 'Price')
->setCellValue('E1', 'VAT')
->setCellValue('F1', 'Total');
// Define named formula
$spreadsheet->addNamedFormula( new \PhpOffice\PhpSpreadsheet\NamedFormula('GERMAN_VAT_RATE', $worksheet, '=16.0%'));
$spreadsheet->addNamedFormula( new \PhpOffice\PhpSpreadsheet\NamedFormula('CALCULATED_PRICE', $worksheet, '=$B1*$C1'));
$spreadsheet->addNamedFormula( new \PhpOffice\PhpSpreadsheet\NamedFormula('GERMAN_VAT', $worksheet, '=$D1*GERMAN_VAT_RATE'));
$spreadsheet->addNamedFormula( new \PhpOffice\PhpSpreadsheet\NamedFormula('TOTAL_INCLUDING_VAT', $worksheet, '=$D1+$E1'));
$worksheet
->setCellValue('A2', 'Advanced Web Application Architecture')
->setCellValue('B2', 2)
->setCellValue('C2', 23.0)
->setCellValue('D2', '=CALCULATED_PRICE')
->setCellValue('E2', '=GERMAN_VAT')
->setCellValue('F2', '=TOTAL_INCLUDING_VAT');
$spreadsheet->getActiveSheet()
->setCellValue('A3', 'Object Design Style Guide')
->setCellValue('B3', 5)
->setCellValue('C3', 12.0)
->setCellValue('D3', '=CALCULATED_PRICE')
->setCellValue('E3', '=GERMAN_VAT')
->setCellValue('F3', '=TOTAL_INCLUDING_VAT');
$spreadsheet->getActiveSheet()
->setCellValue('A4', 'PHP For the Web')
->setCellValue('B4', 3)
->setCellValue('C4', 10.0)
->setCellValue('D4', '=CALCULATED_PRICE')
->setCellValue('E4', '=GERMAN_VAT')
->setCellValue('F4', '=TOTAL_INCLUDING_VAT');
// Use a relative named range to provide the totals for rows 2-4
$spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('COLUMN_TOTAL', $worksheet, '=A$2:A$4') );
$spreadsheet->getActiveSheet()
->setCellValue('B6', '=SUBTOTAL(109,COLUMN_TOTAL)')
->setCellValue('D6', '=SUBTOTAL(109,COLUMN_TOTAL)')
->setCellValue('E6', '=SUBTOTAL(109,COLUMN_TOTAL)')
->setCellValue('F6', '=SUBTOTAL(109,COLUMN_TOTAL)');
```
As with named ranges, an optional fourth parameter can be passed defining the named formula
scope as local (i.e. only usable on the specified worksheet). Otherwise, named formulae are
global by default.
## Redirect output to a client's web browser
2013-05-18 14:56:43 +00:00
Sometimes, one really wants to output a file to a client''s browser,
especially when creating spreadsheets on-the-fly. There are some easy
steps that can be followed to do this:
2013-05-18 14:56:43 +00:00
1. Create your PhpSpreadsheet spreadsheet
2. Output HTTP headers for the type of document you wish to output
2017-12-30 10:44:32 +00:00
3. Use the `\PhpOffice\PhpSpreadsheet\Writer\*` of your choice, and save
2018-01-17 03:10:12 +00:00
to `'php://output'`
2013-05-18 14:56:43 +00:00
2017-12-30 10:44:32 +00:00
`\PhpOffice\PhpSpreadsheet\Writer\Xlsx` uses temporary storage when
2018-01-17 03:10:12 +00:00
writing to `php://output`. By default, temporary files are stored in the
script's working directory. When there is no access, it falls back to
the operating system's temporary files location.
2013-05-18 14:56:43 +00:00
**This may not be safe for unauthorized viewing!** Depending on the
configuration of your operating system, temporary storage can be read by
anyone using the same temporary storage folder. When confidentiality of
2018-01-17 03:10:12 +00:00
your document is needed, it is recommended not to use `php://output`.
2013-05-18 14:56:43 +00:00
### HTTP headers
2013-05-18 14:56:43 +00:00
Example of a script redirecting an Excel 2007 file to the client's
browser:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
/* Here there will be some code where you create $spreadsheet */
2013-05-18 14:56:43 +00:00
// redirect output to client browser
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
2013-05-18 14:56:43 +00:00
```
2016-10-06 11:49:41 +00:00
Example of a script redirecting an Xls file to the client's browser:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
/* Here there will be some code where you create $spreadsheet */
2013-05-18 14:56:43 +00:00
// redirect output to client browser
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myfile.xls"');
header('Cache-Control: max-age=0');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('php://output');
2013-05-18 14:56:43 +00:00
```
**Caution:**
Make sure not to include any echo statements or output any other
contents than the Excel file. There should be no whitespace before the
opening `<?php` tag and at most one line break after the closing `?>`
tag (which can also be omitted to avoid problems). Make sure that your
script is saved without a BOM (Byte-order mark) because this counts as
echoing output. The same things apply to all included files. 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).
2013-05-18 14:56:43 +00:00
## Setting the default column width
2013-05-18 14:56:43 +00:00
Default column width can be set using the following code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);
2013-05-18 14:56:43 +00:00
```
## Setting the default row height
2013-05-18 14:56:43 +00:00
Default row height can be set using the following code:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
2013-05-18 14:56:43 +00:00
```
## Add a GD drawing to a worksheet
2013-05-18 14:56:43 +00:00
There might be a situation where you want to generate an in-memory image
using GD and add it to a `Spreadsheet` without first having to save this
file to a temporary location.
2013-05-18 14:56:43 +00:00
Here''s an example which generates an image in memory and adds it to the
active worksheet:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2013-05-18 14:56:43 +00:00
// Generate an image
$gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream');
$textColor = imagecolorallocate($gdImage, 255, 255, 255);
2016-11-27 15:51:44 +00:00
imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor);
2013-05-18 14:56:43 +00:00
// Add a drawing to the worksheet
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();
$drawing->setName('Sample image');
$drawing->setDescription('Sample image');
$drawing->setImageResource($gdImage);
$drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG);
$drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT);
$drawing->setHeight(36);
$drawing->setWorksheet($spreadsheet->getActiveSheet());
2013-05-18 14:56:43 +00:00
```
## Setting worksheet zoom level
2013-05-18 14:56:43 +00:00
To set a worksheet's zoom level, the following code can be used:
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()->getSheetView()->setZoomScale(75);
2013-05-18 14:56:43 +00:00
```
Note that zoom level should be in range 10 - 400.
2013-05-18 14:56:43 +00:00
## Sheet tab color
2013-05-18 14:56:43 +00:00
Sometimes you want to set a color for sheet tab. For example you can
have a red sheet tab:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
$worksheet->getTabColor()->setRGB('FF0000');
2013-05-18 14:56:43 +00:00
```
## Creating worksheets in a workbook
2013-05-18 14:56:43 +00:00
If you need to create more worksheets in the workbook, here is how:
2020-05-31 13:41:05 +00:00
```php
$worksheet1 = $spreadsheet->createSheet();
$worksheet1->setTitle('Another sheet');
2013-05-18 14:56:43 +00:00
```
2017-12-30 10:44:32 +00:00
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.
2013-05-18 14:56:43 +00:00
## Hidden worksheets (Sheet states)
2013-05-18 14:56:43 +00:00
Set a worksheet to be **hidden** using this code:
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2016-11-27 15:51:44 +00:00
$spreadsheet->getActiveSheet()
->setSheetState(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN);
2013-05-18 14:56:43 +00:00
```
Sometimes you may even want the worksheet to be **"very hidden"**. The
available sheet states are :
2013-05-18 14:56:43 +00:00
- `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VISIBLE`
- `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN`
- `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VERYHIDDEN`
2013-05-18 14:56:43 +00:00
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.
2013-05-18 14:56:43 +00:00
## Right-to-left worksheet
2013-05-18 14:56:43 +00:00
2017-03-13 05:57:37 +00:00
Worksheets can be set individually whether column `A` should start at
left or right side. Default is left. Here is how to set columns from
right-to-left.
2013-05-18 14:56:43 +00:00
2020-05-31 13:41:05 +00:00
```php
2013-05-18 14:56:43 +00:00
// right-to-left worksheet
$spreadsheet->getActiveSheet()->setRightToLeft(true);
2013-05-18 14:56:43 +00:00
```