You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

recipes.md 53 KiB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. # Recipes
  2. The following pages offer you some widely-used PhpSpreadsheet recipes.
  3. Please note that these do NOT offer complete documentation on specific
  4. PhpSpreadsheet API functions, but just a bump to get you started. If you
  5. need specific API functions, please refer to the [API documentation](https://phpoffice.github.io/PhpSpreadsheet).
  6. For example, [setting a worksheet's page orientation and size
  7. ](#setting-a-worksheets-page-orientation-and-size) covers setting a page
  8. orientation to A4. Other paper formats, like US Letter, are not covered
  9. in this document, but in the PhpSpreadsheet [API documentation](https://phpoffice.github.io/PhpSpreadsheet).
  10. ## Setting a spreadsheet's metadata
  11. PhpSpreadsheet allows an easy way to set a spreadsheet's metadata, using
  12. document property accessors. Spreadsheet metadata can be useful for
  13. finding a specific document in a file repository or a document
  14. management system. For example Microsoft Sharepoint uses document
  15. metadata to search for a specific document in its document lists.
  16. Setting spreadsheet metadata is done as follows:
  17. ``` php
  18. $spreadsheet->getProperties()
  19. ->setCreator("Maarten Balliauw")
  20. ->setLastModifiedBy("Maarten Balliauw")
  21. ->setTitle("Office 2007 XLSX Test Document")
  22. ->setSubject("Office 2007 XLSX Test Document")
  23. ->setDescription(
  24. "Test document for Office 2007 XLSX, generated using PHP classes."
  25. )
  26. ->setKeywords("office 2007 openxml php")
  27. ->setCategory("Test result file");
  28. ```
  29. ## Setting a spreadsheet's active sheet
  30. The following line of code sets the active sheet index to the first
  31. sheet:
  32. ``` php
  33. $spreadsheet->setActiveSheetIndex(0);
  34. ```
  35. You can also set the active sheet by its name/title
  36. ``` php
  37. $spreadsheet->setActiveSheetIndexByName('DataSheet')
  38. ```
  39. will change the currently active sheet to the worksheet called
  40. "DataSheet".
  41. ## Write a date or time into a cell
  42. In Excel, dates and Times are stored as numeric values counting the
  43. number of days elapsed since 1900-01-01. For example, the date
  44. '2008-12-31' is represented as 39813. You can verify this in Microsoft
  45. Office Excel by entering that date in a cell and afterwards changing the
  46. number format to 'General' so the true numeric value is revealed.
  47. Likewise, '3:15 AM' is represented as 0.135417.
  48. PhpSpreadsheet works with UST (Universal Standard Time) date and Time
  49. values, but does no internal conversions; so it is up to the developer
  50. to ensure that values passed to the date/time conversion functions are
  51. UST.
  52. Writing a date value in a cell consists of 2 lines of code. Select the
  53. method that suits you the best. Here are some examples:
  54. ``` php
  55. // MySQL-like timestamp '2008-12-31' or date string
  56. \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
  57. $spreadsheet->getActiveSheet()
  58. ->setCellValue('D1', '2008-12-31');
  59. $spreadsheet->getActiveSheet()->getStyle('D1')
  60. ->getNumberFormat()
  61. ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
  62. // PHP-time (Unix time)
  63. $time = gmmktime(0,0,0,12,31,2008); // int(1230681600)
  64. $spreadsheet->getActiveSheet()
  65. ->setCellValue('D1', \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($time));
  66. $spreadsheet->getActiveSheet()->getStyle('D1')
  67. ->getNumberFormat()
  68. ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
  69. // Excel-date/time
  70. $spreadsheet->getActiveSheet()->setCellValue('D1', 39813)
  71. $spreadsheet->getActiveSheet()->getStyle('D1')
  72. ->getNumberFormat()
  73. ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
  74. ```
  75. The above methods for entering a date all yield the same result.
  76. `\PhpOffice\PhpSpreadsheet\Style\NumberFormat` provides a lot of
  77. pre-defined date formats.
  78. The `\PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel()` method will also
  79. work with a PHP DateTime object.
  80. Similarly, times (or date and time values) can be entered in the same
  81. fashion: just remember to use an appropriate format code.
  82. **Note:**
  83. See section "Using value binders to facilitate data entry" to learn more
  84. about the AdvancedValueBinder used in the first example. Excel can also
  85. operate in a 1904-based calendar (default for workbooks saved on Mac).
  86. Normally, you do not have to worry about this when using PhpSpreadsheet.
  87. ## Write a formula into a cell
  88. Inside the Excel file, formulas are always stored as they would appear
  89. in an English version of Microsoft Office Excel, and PhpSpreadsheet
  90. handles all formulae internally in this format. This means that the
  91. following rules hold:
  92. - Decimal separator is `.` (period)
  93. - Function argument separator is `,` (comma)
  94. - Matrix row separator is `;` (semicolon)
  95. - English function names must be used
  96. This is regardless of which language version of Microsoft Office Excel
  97. may have been used to create the Excel file.
  98. When the final workbook is opened by the user, Microsoft Office Excel
  99. will take care of displaying the formula according the applications
  100. language. Translation is taken care of by the application!
  101. The following line of code writes the formula
  102. `=IF(C4>500,"profit","loss")` into the cell B8. Note that the
  103. formula must start with `=` to make PhpSpreadsheet recognise this as a
  104. formula.
  105. ``` php
  106. $spreadsheet->getActiveSheet()->setCellValue('B8','=IF(C4>500,"profit","loss")');
  107. ```
  108. If you want to write a string beginning with an `=` character to a
  109. cell, then you should use the `setCellValueExplicit()` method.
  110. ``` php
  111. $spreadsheet->getActiveSheet()
  112. ->setCellValueExplicit(
  113. 'B8',
  114. '=IF(C4>500,"profit","loss")',
  115. \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING
  116. );
  117. ```
  118. A cell's formula can be read again using the following line of code:
  119. ``` php
  120. $formula = $spreadsheet->getActiveSheet()->getCell('B8')->getValue();
  121. ```
  122. If you need the calculated value of a cell, use the following code. This
  123. is further explained in [the calculation engine](./calculation-engine.md).
  124. ``` php
  125. $value = $spreadsheet->getActiveSheet()->getCell('B8')->getCalculatedValue();
  126. ```
  127. ## Locale Settings for Formulae
  128. Some localisation elements have been included in PhpSpreadsheet. You can
  129. set a locale by changing the settings. To set the locale to Russian you
  130. would use:
  131. ``` php
  132. $locale = 'ru';
  133. $validLocale = \PhpOffice\PhpSpreadsheet\Settings::setLocale($locale);
  134. if (!$validLocale) {
  135. echo 'Unable to set locale to '.$locale." - reverting to en_us<br />\n";
  136. }
  137. ```
  138. If Russian language files aren't available, the `setLocale()` method
  139. will return an error, and English settings will be used throughout.
  140. Once you have set a locale, you can translate a formula from its
  141. internal English coding.
  142. ``` php
  143. $formula = $spreadsheet->getActiveSheet()->getCell('B8')->getValue();
  144. $translatedFormula = \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance()->_translateFormulaToLocale($formula);
  145. ```
  146. You can also create a formula using the function names and argument
  147. separators appropriate to the defined locale; then translate it to
  148. English before setting the cell value:
  149. ``` php
  150. $formula = '=ДНЕЙ360(ДАТА(2010;2;5);ДАТА(2010;12;31);ИСТИНА)';
  151. $internalFormula = \PhpOffice\PhpSpreadsheet\Calculation\Calculation::getInstance()->translateFormulaToEnglish($formula);
  152. $spreadsheet->getActiveSheet()->setCellValue('B8',$internalFormula);
  153. ```
  154. Currently, formula translation only translates the function names, the
  155. constants TRUE and FALSE, and the function argument separators.
  156. At present, the following locale settings are supported:
  157. Language | | Locale Code
  158. ---------------------|----------------------|-------------
  159. Czech | Ceština | cs
  160. Danish | Dansk | da
  161. German | Deutsch | de
  162. Spanish | Español | es
  163. Finnish | Suomi | fi
  164. French | Français | fr
  165. Hungarian | Magyar | hu
  166. Italian | Italiano | it
  167. Dutch | Nederlands | nl
  168. Norwegian | Norsk | no
  169. Polish | Jezyk polski | pl
  170. Portuguese | Português | pt
  171. Brazilian Portuguese | Português Brasileiro | pt_br
  172. Russian | русский язык | ru
  173. Swedish | Svenska | sv
  174. Turkish | Türkçe | tr
  175. ## Write a newline character "\n" in a cell (ALT+"Enter")
  176. In Microsoft Office Excel you get a line break in a cell by hitting
  177. ALT+"Enter". When you do that, it automatically turns on "wrap text" for
  178. the cell.
  179. Here is how to achieve this in PhpSpreadsheet:
  180. ``` php
  181. $spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
  182. $spreadsheet->getActiveSheet()->getStyle('A1')->getAlignment()->setWrapText(true);
  183. ```
  184. **Tip**
  185. Read more about formatting cells using `getStyle()` elsewhere.
  186. **Tip**
  187. AdvancedValuebinder.php automatically turns on "wrap text" for the cell
  188. when it sees a newline character in a string that you are inserting in a
  189. cell. Just like Microsoft Office Excel. Try this:
  190. ``` php
  191. \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
  192. $spreadsheet->getActiveSheet()->getCell('A1')->setValue("hello\nworld");
  193. ```
  194. Read more about AdvancedValueBinder.php elsewhere.
  195. ## Explicitly set a cell's datatype
  196. You can set a cell's datatype explicitly by using the cell's
  197. setValueExplicit method, or the setCellValueExplicit method of a
  198. worksheet. Here's an example:
  199. ``` php
  200. $spreadsheet->getActiveSheet()->getCell('A1')
  201. ->setValueExplicit(
  202. '25',
  203. \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC
  204. );
  205. ```
  206. ## Change a cell into a clickable URL
  207. You can make a cell a clickable URL by setting its hyperlink property:
  208. ``` php
  209. $spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
  210. $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl('https://www.example.com');
  211. ```
  212. If you want to make a hyperlink to another worksheet/cell, use the
  213. following code:
  214. ``` php
  215. $spreadsheet->getActiveSheet()->setCellValue('E26', 'www.phpexcel.net');
  216. $spreadsheet->getActiveSheet()->getCell('E26')->getHyperlink()->setUrl("sheet://'Sheetname'!A1");
  217. ```
  218. ## Setting Printer Options for Excel files
  219. ### Setting a worksheet's page orientation and size
  220. Setting a worksheet's page orientation and size can be done using the
  221. following lines of code:
  222. ``` php
  223. $spreadsheet->getActiveSheet()->getPageSetup()
  224. ->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
  225. $spreadsheet->getActiveSheet()->getPageSetup()
  226. ->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4);
  227. ```
  228. Note that there are additional page settings available. Please refer to
  229. the [API documentation](https://phpoffice.github.io/PhpSpreadsheet) for all possible options.
  230. ### Page Setup: Scaling options
  231. The page setup scaling options in PhpSpreadsheet relate directly to the
  232. scaling options in the "Page Setup" dialog as shown in the illustration.
  233. Default values in PhpSpreadsheet correspond to default values in MS
  234. Office Excel as shown in illustration
  235. ![08-page-setup-scaling-options.png](./images/08-page-setup-scaling-options.png)
  236. method | initial value | calling method will trigger | Note
  237. --------------------|:-------------:|-----------------------------|------
  238. setFitToPage(...) | FALSE | - |
  239. setScale(...) | 100 | setFitToPage(FALSE) |
  240. setFitToWidth(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-width
  241. setFitToHeight(...) | 1 | setFitToPage(TRUE) | value 0 means do-not-fit-to-height
  242. #### Example
  243. Here is how to fit to 1 page wide by infinite pages tall:
  244. ``` php
  245. $spreadsheet->getActiveSheet()->getPageSetup()->setFitToWidth(1);
  246. $spreadsheet->getActiveSheet()->getPageSetup()->setFitToHeight(0);
  247. ```
  248. As you can see, it is not necessary to call setFitToPage(TRUE) since
  249. setFitToWidth(...) and setFitToHeight(...) triggers this.
  250. If you use `setFitToWidth()` you should in general also specify
  251. `setFitToHeight()` explicitly like in the example. Be careful relying on
  252. the initial values.
  253. ### Page margins
  254. To set page margins for a worksheet, use this code:
  255. ``` php
  256. $spreadsheet->getActiveSheet()->getPageMargins()->setTop(1);
  257. $spreadsheet->getActiveSheet()->getPageMargins()->setRight(0.75);
  258. $spreadsheet->getActiveSheet()->getPageMargins()->setLeft(0.75);
  259. $spreadsheet->getActiveSheet()->getPageMargins()->setBottom(1);
  260. ```
  261. Note that the margin values are specified in inches.
  262. ![08-page-setup-margins.png](./images/08-page-setup-margins.png)
  263. ### Center a page horizontally/vertically
  264. To center a page horizontally/vertically, you can use the following
  265. code:
  266. ``` php
  267. $spreadsheet->getActiveSheet()->getPageSetup()->setHorizontalCentered(true);
  268. $spreadsheet->getActiveSheet()->getPageSetup()->setVerticalCentered(false);
  269. ```
  270. ### Setting the print header and footer of a worksheet
  271. Setting a worksheet's print header and footer can be done using the
  272. following lines of code:
  273. ``` php
  274. $spreadsheet->getActiveSheet()->getHeaderFooter()
  275. ->setOddHeader('&C&HPlease treat this document as confidential!');
  276. $spreadsheet->getActiveSheet()->getHeaderFooter()
  277. ->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N');
  278. ```
  279. Substitution and formatting codes (starting with &) can be used inside
  280. headers and footers. There is no required order in which these codes
  281. must appear.
  282. The first occurrence of the following codes turns the formatting ON, the
  283. second occurrence turns it OFF again:
  284. - Strikethrough
  285. - Superscript
  286. - Subscript
  287. Superscript and subscript cannot both be ON at same time. Whichever
  288. comes first wins and the other is ignored, while the first is ON.
  289. The following codes are supported by Xlsx:
  290. Code | Meaning
  291. -------------------------|-----------
  292. `&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.
  293. `&P` | Code for "current page #"
  294. `&N` | Code for "total pages"
  295. `&font size` | Code for "text font size", where font size is a font size in points.
  296. `&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.
  297. `&S` | Code for "text strikethrough" on / off
  298. `&X` | Code for "text super script" on / off
  299. `&Y` | Code for "text subscript" on / off
  300. `&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.
  301. `&D` | Code for "date"
  302. `&T` | Code for "time"
  303. `&G` | Code for "picture as background" - Please make sure to add the image to the header/footer (see Tip for picture)
  304. `&U` | Code for "text single underline"
  305. `&E` | Code for "double underline"
  306. `&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.
  307. `&Z` | Code for "this workbook's file path"
  308. `&F` | Code for "this workbook's file name"
  309. `&A` | Code for "sheet tab name"
  310. `&+` | Code for add to page #
  311. `&-` | Code for subtract from page #
  312. `&"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.
  313. `&"-,Bold"` | Code for "bold font style"
  314. `&B` | Code for "bold font style"
  315. `&"-,Regular"` | Code for "regular font style"
  316. `&"-,Italic"` | Code for "italic font style"
  317. `&I` | Code for "italic font style"
  318. `&"-,Bold Italic"` | Code for "bold italic font style"
  319. `&O` | Code for "outline style"
  320. `&H` | Code for "shadow style"
  321. **Tip**
  322. The above table of codes may seem overwhelming first time you are trying to
  323. figure out how to write some header or footer. Luckily, there is an easier way.
  324. Let Microsoft Office Excel do the work for you.For example, create in Microsoft
  325. Office Excel an xlsx file where you insert the header and footer as desired
  326. using the programs own interface. Save file as test.xlsx. Now, take that file
  327. and read off the values using PhpSpreadsheet as follows:
  328. ```php
  329. $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('test.xlsx');
  330. $worksheet = $spreadsheet->getActiveSheet();
  331. var_dump($worksheet->getHeaderFooter()->getOddFooter());
  332. var_dump($worksheet->getHeaderFooter()->getEvenFooter());
  333. var_dump($worksheet->getHeaderFooter()->getOddHeader());
  334. var_dump($worksheet->getHeaderFooter()->getEvenHeader());
  335. ```
  336. That reveals the codes for the even/odd header and footer. Experienced
  337. users may find it easier to rename test.xlsx to test.zip, unzip it, and
  338. inspect directly the contents of the relevant xl/worksheets/sheetX.xml
  339. to find the codes for header/footer.
  340. **Tip for picture**
  341. ```php
  342. $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing();
  343. $drawing->setName('PhpSpreadsheet logo');
  344. $drawing->setPath('./images/PhpSpreadsheet_logo.png');
  345. $drawing->setHeight(36);
  346. $spreadsheet->getActiveSheet()->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT);
  347. ```
  348. ### Setting printing breaks on a row or column
  349. To set a print break, use the following code, which sets a row break on
  350. row 10.
  351. ``` php
  352. $spreadsheet->getActiveSheet()->setBreak('A10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW);
  353. ```
  354. The following line of code sets a print break on column D:
  355. ``` php
  356. $spreadsheet->getActiveSheet()->setBreak('D10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_COLUMN);
  357. ```
  358. ### Show/hide gridlines when printing
  359. To show/hide gridlines when printing, use the following code:
  360. ```php
  361. $spreadsheet->getActiveSheet()->setShowGridlines(true);
  362. ```
  363. ### Setting rows/columns to repeat at top/left
  364. PhpSpreadsheet can repeat specific rows/cells at top/left of a page. The
  365. following code is an example of how to repeat row 1 to 5 on each printed
  366. page of a specific worksheet:
  367. ``` php
  368. $spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
  369. ```
  370. ### Specify printing area
  371. To specify a worksheet's printing area, use the following code:
  372. ``` php
  373. $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5');
  374. ```
  375. There can also be multiple printing areas in a single worksheet:
  376. ``` php
  377. $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:E5,G4:M20');
  378. ```
  379. ## Styles
  380. ### Formatting cells
  381. A cell can be formatted with font, border, fill, ... style information.
  382. For example, one can set the foreground colour of a cell to red, aligned
  383. to the right, and the border to black and thick border style. Let's do
  384. that on cell B2:
  385. ``` php
  386. $spreadsheet->getActiveSheet()->getStyle('B2')
  387. ->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
  388. $spreadsheet->getActiveSheet()->getStyle('B2')
  389. ->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT);
  390. $spreadsheet->getActiveSheet()->getStyle('B2')
  391. ->getBorders()->getTop()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK);
  392. $spreadsheet->getActiveSheet()->getStyle('B2')
  393. ->getBorders()->getBottom()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK);
  394. $spreadsheet->getActiveSheet()->getStyle('B2')
  395. ->getBorders()->getLeft()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK);
  396. $spreadsheet->getActiveSheet()->getStyle('B2')
  397. ->getBorders()->getRight()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK);
  398. $spreadsheet->getActiveSheet()->getStyle('B2')
  399. ->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
  400. $spreadsheet->getActiveSheet()->getStyle('B2')
  401. ->getFill()->getStartColor()->setARGB('FFFF0000');
  402. ```
  403. `getStyle()` also accepts a cell range as a parameter. For example, you
  404. can set a red background color on a range of cells:
  405. ``` php
  406. $spreadsheet->getActiveSheet()->getStyle('B3:B7')->getFill()
  407. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  408. ->getStartColor()->setARGB('FFFF0000');
  409. ```
  410. **Tip** It is recommended to style many cells at once, using e.g.
  411. getStyle('A1:M500'), rather than styling the cells individually in a
  412. loop. This is much faster compared to looping through cells and styling
  413. them individually.
  414. There is also an alternative manner to set styles. The following code
  415. sets a cell's style to font bold, alignment right, top border thin and a
  416. gradient fill:
  417. ``` php
  418. $styleArray = [
  419. 'font' => [
  420. 'bold' => true,
  421. ],
  422. 'alignment' => [
  423. 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT,
  424. ],
  425. 'borders' => [
  426. 'top' => [
  427. 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
  428. ],
  429. ],
  430. 'fill' => [
  431. 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR,
  432. 'rotation' => 90,
  433. 'startColor' => [
  434. 'argb' => 'FFA0A0A0',
  435. ],
  436. 'endColor' => [
  437. 'argb' => 'FFFFFFFF',
  438. ],
  439. ],
  440. ];
  441. $spreadsheet->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray);
  442. ```
  443. Or with a range of cells:
  444. ``` php
  445. $spreadsheet->getActiveSheet()->getStyle('B3:B7')->applyFromArray($styleArray);
  446. ```
  447. This alternative method using arrays should be faster in terms of
  448. execution whenever you are setting more than one style property. But the
  449. difference may barely be measurable unless you have many different
  450. styles in your workbook.
  451. ### Number formats
  452. You often want to format numbers in Excel. For example you may want a
  453. thousands separator plus a fixed number of decimals after the decimal
  454. separator. Or perhaps you want some numbers to be zero-padded.
  455. In Microsoft Office Excel you may be familiar with selecting a number
  456. format from the "Format Cells" dialog. Here there are some predefined
  457. number formats available including some for dates. The dialog is
  458. designed in a way so you don't have to interact with the underlying raw
  459. number format code unless you need a custom number format.
  460. In PhpSpreadsheet, you can also apply various predefined number formats.
  461. Example:
  462. ``` php
  463. $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()
  464. ->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
  465. ```
  466. This will format a number e.g. 1587.2 so it shows up as 1,587.20 when
  467. you open the workbook in MS Office Excel. (Depending on settings for
  468. decimal and thousands separators in Microsoft Office Excel it may show
  469. up as 1.587,20)
  470. You can achieve exactly the same as the above by using this:
  471. ``` php
  472. $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()
  473. ->setFormatCode('#,##0.00');
  474. ```
  475. In Microsoft Office Excel, as well as in PhpSpreadsheet, you will have
  476. to interact with raw number format codes whenever you need some special
  477. custom number format. Example:
  478. ``` php
  479. $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()
  480. ->setFormatCode('[Blue][>=3000]$#,##0;[Red][<0]$#,##0;$#,##0');
  481. ```
  482. Another example is when you want numbers zero-padded with leading zeros
  483. to a fixed length:
  484. ``` php
  485. $spreadsheet->getActiveSheet()->getCell('A1')->setValue(19);
  486. $spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()
  487. ->setFormatCode('0000'); // will show as 0019 in Excel
  488. ```
  489. **Tip** The rules for composing a number format code in Excel can be
  490. rather complicated. Sometimes you know how to create some number format
  491. in Microsoft Office Excel, but don't know what the underlying number
  492. format code looks like. How do you find it?
  493. The readers shipped with PhpSpreadsheet come to the rescue. Load your
  494. template workbook using e.g. Xlsx reader to reveal the number format
  495. code. Example how read a number format code for cell A1:
  496. ``` php
  497. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
  498. $spreadsheet = $reader->load('template.xlsx');
  499. var_dump($spreadsheet->getActiveSheet()->getStyle('A1')->getNumberFormat()->getFormatCode());
  500. ```
  501. Advanced users may find it faster to inspect the number format code
  502. directly by renaming template.xlsx to template.zip, unzipping, and
  503. looking for the relevant piece of XML code holding the number format
  504. code in *xl/styles.xml*.
  505. ### Alignment and wrap text
  506. Let's set vertical alignment to the top for cells A1:D4
  507. ``` php
  508. $spreadsheet->getActiveSheet()->getStyle('A1:D4')
  509. ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  510. ```
  511. Here is how to achieve wrap text:
  512. ``` php
  513. $spreadsheet->getActiveSheet()->getStyle('A1:D4')
  514. ->getAlignment()->setWrapText(true);
  515. ```
  516. ### Setting the default style of a workbook
  517. It is possible to set the default style of a workbook. Let's set the
  518. default font to Arial size 8:
  519. ``` php
  520. $spreadsheet->getDefaultStyle()->getFont()->setName('Arial');
  521. $spreadsheet->getDefaultStyle()->getFont()->setSize(8);
  522. ```
  523. ### Styling cell borders
  524. In PhpSpreadsheet it is easy to apply various borders on a rectangular
  525. selection. Here is how to apply a thick red border outline around cells
  526. B2:G8.
  527. ``` php
  528. $styleArray = [
  529. 'borders' => [
  530. 'outline' => [
  531. 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
  532. 'color' => ['argb' => 'FFFF0000'],
  533. ],
  534. ],
  535. ];
  536. $worksheet->getStyle('B2:G8')->applyFromArray($styleArray);
  537. ```
  538. In Microsoft Office Excel, the above operation would correspond to
  539. selecting the cells B2:G8, launching the style dialog, choosing a thick
  540. red border, and clicking on the "Outline" border component.
  541. Note that the border outline is applied to the rectangular selection
  542. B2:G8 as a whole, not on each cell individually.
  543. You can achieve any border effect by using just the 5 basic borders and
  544. operating on a single cell at a time:
  545. - left
  546. - right
  547. - top
  548. - bottom
  549. - diagonal
  550. Additional shortcut borders come in handy like in the example above.
  551. These are the shortcut borders available:
  552. - allBorders
  553. - outline
  554. - inside
  555. - vertical
  556. - horizontal
  557. An overview of all border shortcuts can be seen in the following image:
  558. ![08-styling-border-options.png](./images/08-styling-border-options.png)
  559. If you simultaneously set e.g. allBorders and vertical, then we have
  560. "overlapping" borders, and one of the components has to win over the
  561. other where there is border overlap. In PhpSpreadsheet, from weakest to
  562. strongest borders, the list is as follows: allBorders, outline/inside,
  563. vertical/horizontal, left/right/top/bottom/diagonal.
  564. This border hierarchy can be utilized to achieve various effects in an
  565. easy manner.
  566. ### Valid array keys for style `applyFromArray()`
  567. The following table lists the valid array keys for
  568. `\PhpOffice\PhpSpreadsheet\Style\Style::applyFromArray()` classes. If the "Maps
  569. to property" column maps a key to a setter, the value provided for that
  570. key will be applied directly. If the "Maps to property" column maps a
  571. key to a getter, the value provided for that key will be applied as
  572. another style array.
  573. **\PhpOffice\PhpSpreadsheet\Style\Style**
  574. Array key | Maps to property
  575. -------------|-------------------
  576. fill | getFill()
  577. font | getFont()
  578. borders | getBorders()
  579. alignment | getAlignment()
  580. numberFormat | getNumberFormat()
  581. protection | getProtection()
  582. **\PhpOffice\PhpSpreadsheet\Style\Fill**
  583. Array key | Maps to property
  584. -----------|-------------------
  585. fillType | setFillType()
  586. rotation | setRotation()
  587. startColor | getStartColor()
  588. endColor | getEndColor()
  589. color | getStartColor()
  590. **\PhpOffice\PhpSpreadsheet\Style\Font**
  591. Array key | Maps to property
  592. ------------|-------------------
  593. name | setName()
  594. bold | setBold()
  595. italic | setItalic()
  596. underline | setUnderline()
  597. strikethrough | setStrikethrough()
  598. color | getColor()
  599. size | setSize()
  600. superscript | setSuperscript()
  601. subscript | setSubscript()
  602. **\PhpOffice\PhpSpreadsheet\Style\Borders**
  603. Array key | Maps to property
  604. ------------------|-------------------
  605. allBorders | getLeft(); getRight(); getTop(); getBottom()
  606. left | getLeft()
  607. right | getRight()
  608. top | getTop()
  609. bottom | getBottom()
  610. diagonal | getDiagonal()
  611. vertical | getVertical()
  612. horizontal | getHorizontal()
  613. diagonalDirection | setDiagonalDirection()
  614. outline | setOutline()
  615. **\PhpOffice\PhpSpreadsheet\Style\Border**
  616. Array key | Maps to property
  617. ------------|-------------------
  618. borderStyle | setBorderStyle()
  619. color | getColor()
  620. **\PhpOffice\PhpSpreadsheet\Style\Alignment**
  621. Array key | Maps to property
  622. ------------|-------------------
  623. horizontal | setHorizontal()
  624. vertical | setVertical()
  625. textRotation| setTextRotation()
  626. wrapText | setWrapText()
  627. shrinkToFit | setShrinkToFit()
  628. indent | setIndent()
  629. **\PhpOffice\PhpSpreadsheet\Style\NumberFormat**
  630. Array key | Maps to property
  631. ----------|-------------------
  632. formatCode | setFormatCode()
  633. **\PhpOffice\PhpSpreadsheet\Style\Protection**
  634. Array key | Maps to property
  635. ----------|-------------------
  636. locked | setLocked()
  637. hidden | setHidden()
  638. ## Conditional formatting a cell
  639. A cell can be formatted conditionally, based on a specific rule. For
  640. example, one can set the foreground colour of a cell to red if its value
  641. is below zero, and to green if its value is zero or more.
  642. One can set a conditional style ruleset to a cell using the following
  643. code:
  644. ``` php
  645. $conditional1 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
  646. $conditional1->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS);
  647. $conditional1->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_LESSTHAN);
  648. $conditional1->addCondition('0');
  649. $conditional1->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
  650. $conditional1->getStyle()->getFont()->setBold(true);
  651. $conditional2 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
  652. $conditional2->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS);
  653. $conditional2->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_GREATERTHANOREQUAL);
  654. $conditional2->addCondition('0');
  655. $conditional2->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_GREEN);
  656. $conditional2->getStyle()->getFont()->setBold(true);
  657. $conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('B2')->getConditionalStyles();
  658. $conditionalStyles[] = $conditional1;
  659. $conditionalStyles[] = $conditional2;
  660. $spreadsheet->getActiveSheet()->getStyle('B2')->setConditionalStyles($conditionalStyles);
  661. ```
  662. If you want to copy the ruleset to other cells, you can duplicate the
  663. style object:
  664. ``` php
  665. $spreadsheet->getActiveSheet()
  666. ->duplicateStyle(
  667. $spreadsheet->getActiveSheet()->getStyle('B2'),
  668. 'B3:B7'
  669. );
  670. ```
  671. ## Add a comment to a cell
  672. To add a comment to a cell, use the following code. The example below
  673. adds a comment to cell E11:
  674. ``` php
  675. $spreadsheet->getActiveSheet()
  676. ->getComment('E11')
  677. ->setAuthor('Mark Baker');
  678. $commentRichText = $spreadsheet->getActiveSheet()
  679. ->getComment('E11')
  680. ->getText()->createTextRun('PhpSpreadsheet:');
  681. $commentRichText->getFont()->setBold(true);
  682. $spreadsheet->getActiveSheet()
  683. ->getComment('E11')
  684. ->getText()->createTextRun("\r\n");
  685. $spreadsheet->getActiveSheet()
  686. ->getComment('E11')
  687. ->getText()->createTextRun('Total amount on the current invoice, excluding VAT.');
  688. ```
  689. ![08-cell-comment.png](./images/08-cell-comment.png)
  690. ## Apply autofilter to a range of cells
  691. To apply an autofilter to a range of cells, use the following code:
  692. ``` php
  693. $spreadsheet->getActiveSheet()->setAutoFilter('A1:C9');
  694. ```
  695. **Make sure that you always include the complete filter range!** Excel
  696. does support setting only the captionrow, but that's **not** a best
  697. practice...
  698. ## Setting security on a spreadsheet
  699. Excel offers 3 levels of "protection":
  700. - Document: allows you to set a password on a complete
  701. spreadsheet, allowing changes to be made only when that password is
  702. entered.
  703. - Worksheet: offers other security options: you can
  704. disallow inserting rows on a specific sheet, disallow sorting, ...
  705. - Cell: offers the option to lock/unlock a cell as well as show/hide
  706. the internal formula.
  707. An example on setting document security:
  708. ``` php
  709. $spreadsheet->getSecurity()->setLockWindows(true);
  710. $spreadsheet->getSecurity()->setLockStructure(true);
  711. $spreadsheet->getSecurity()->setWorkbookPassword("PhpSpreadsheet");
  712. ```
  713. An example on setting worksheet security:
  714. ``` php
  715. $spreadsheet->getActiveSheet()
  716. ->getProtection()->setPassword('PhpSpreadsheet');
  717. $spreadsheet->getActiveSheet()
  718. ->getProtection()->setSheet(true);
  719. $spreadsheet->getActiveSheet()
  720. ->getProtection()->setSort(true);
  721. $spreadsheet->getActiveSheet()
  722. ->getProtection()->setInsertRows(true);
  723. $spreadsheet->getActiveSheet()
  724. ->getProtection()->setFormatCells(true);
  725. ```
  726. An example on setting cell security:
  727. ``` php
  728. $spreadsheet->getActiveSheet()->getStyle('B1')
  729. ->getProtection()
  730. ->setLocked(\PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_UNPROTECTED);
  731. ```
  732. **Make sure you enable worksheet protection if you need any of the
  733. worksheet protection features!** This can be done using the following
  734. code:
  735. ``` php
  736. $spreadsheet->getActiveSheet()->getProtection()->setSheet(true);
  737. ```
  738. ## Setting data validation on a cell
  739. Data validation is a powerful feature of Xlsx. It allows to specify an
  740. input filter on the data that can be inserted in a specific cell. This
  741. filter can be a range (i.e. value must be between 0 and 10), a list
  742. (i.e. value must be picked from a list), ...
  743. The following piece of code only allows numbers between 10 and 20 to be
  744. entered in cell B3:
  745. ``` php
  746. $validation = $spreadsheet->getActiveSheet()->getCell('B3')
  747. ->getDataValidation();
  748. $validation->setType( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_WHOLE );
  749. $validation->setErrorStyle( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_STOP );
  750. $validation->setAllowBlank(true);
  751. $validation->setShowInputMessage(true);
  752. $validation->setShowErrorMessage(true);
  753. $validation->setErrorTitle('Input error');
  754. $validation->setError('Number is not allowed!');
  755. $validation->setPromptTitle('Allowed input');
  756. $validation->setPrompt('Only numbers between 10 and 20 are allowed.');
  757. $validation->setFormula1(10);
  758. $validation->setFormula2(20);
  759. ```
  760. The following piece of code only allows an item picked from a list of
  761. data to be entered in cell B5:
  762. ``` php
  763. $validation = $spreadsheet->getActiveSheet()->getCell('B5')
  764. ->getDataValidation();
  765. $validation->setType( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_LIST );
  766. $validation->setErrorStyle( \PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_INFORMATION );
  767. $validation->setAllowBlank(false);
  768. $validation->setShowInputMessage(true);
  769. $validation->setShowErrorMessage(true);
  770. $validation->setShowDropDown(true);
  771. $validation->setErrorTitle('Input error');
  772. $validation->setError('Value is not in list.');
  773. $validation->setPromptTitle('Pick from list');
  774. $validation->setPrompt('Please pick a value from the drop-down list.');
  775. $validation->setFormula1('"Item A,Item B,Item C"');
  776. ```
  777. When using a data validation list like above, make sure you put the list
  778. between `"` and `"` and that you split the items with a comma (`,`).
  779. It is important to remember that any string participating in an Excel
  780. formula is allowed to be maximum 255 characters (not bytes). This sets a
  781. limit on how many items you can have in the string "Item A,Item B,Item
  782. C". Therefore it is normally a better idea to type the item values
  783. directly in some cell range, say A1:A3, and instead use, say,
  784. `$validation->setFormula1('Sheet!$A$1:$A$3')`. Another benefit is that
  785. the item values themselves can contain the comma `,` character itself.
  786. If you need data validation on multiple cells, one can clone the
  787. ruleset:
  788. ``` php
  789. $spreadsheet->getActiveSheet()->getCell('B8')->setDataValidation(clone $validation);
  790. ```
  791. ## Setting a column's width
  792. A column's width can be set using the following code:
  793. ``` php
  794. $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(12);
  795. ```
  796. If you want PhpSpreadsheet to perform an automatic width calculation,
  797. use the following code. PhpSpreadsheet will approximate the column with
  798. to the width of the widest column value.
  799. ``` php
  800. $spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
  801. ```
  802. ![08-column-width.png](./images/08-column-width.png)
  803. The measure for column width in PhpSpreadsheet does **not** correspond
  804. exactly to the measure you may be used to in Microsoft Office Excel.
  805. Column widths are difficult to deal with in Excel, and there are several
  806. measures for the column width.
  807. 1. Inner width in character units
  808. (e.g. 8.43 this is probably what you are familiar with in Excel)
  809. 2. Full width in pixels (e.g. 64 pixels)
  810. 3. Full width in character units (e.g. 9.140625, value -1 indicates unset width)
  811. **PhpSpreadsheet always
  812. operates with "3. Full width in character units"** which is in fact the
  813. only value that is stored in any Excel file, hence the most reliable
  814. measure. Unfortunately, **Microsoft Office Excel does not present you
  815. with this measure**. Instead measures 1 and 2 are computed by the
  816. application when the file is opened and these values are presented in
  817. various dialogues and tool tips.
  818. The character width unit is the width of
  819. a `0` (zero) glyph in the workbooks default font. Therefore column
  820. widths measured in character units in two different workbooks can only
  821. be compared if they have the same default workbook font.If you have some
  822. Excel file and need to know the column widths in measure 3, you can
  823. read the Excel file with PhpSpreadsheet and echo the retrieved values.
  824. ## Show/hide a column
  825. To set a worksheet's column visibility, you can use the following code.
  826. The first line explicitly shows the column C, the second line hides
  827. column D.
  828. ``` php
  829. $spreadsheet->getActiveSheet()->getColumnDimension('C')->setVisible(true);
  830. $spreadsheet->getActiveSheet()->getColumnDimension('D')->setVisible(false);
  831. ```
  832. ## Group/outline a column
  833. To group/outline a column, you can use the following code:
  834. ``` php
  835. $spreadsheet->getActiveSheet()->getColumnDimension('E')->setOutlineLevel(1);
  836. ```
  837. You can also collapse the column. Note that you should also set the
  838. column invisible, otherwise the collapse will not be visible in Excel
  839. 2007.
  840. ``` php
  841. $spreadsheet->getActiveSheet()->getColumnDimension('E')->setCollapsed(true);
  842. $spreadsheet->getActiveSheet()->getColumnDimension('E')->setVisible(false);
  843. ```
  844. Please refer to the section "group/outline a row" for a complete example
  845. on collapsing.
  846. You can instruct PhpSpreadsheet to add a summary to the right (default),
  847. or to the left. The following code adds the summary to the left:
  848. ``` php
  849. $spreadsheet->getActiveSheet()->setShowSummaryRight(false);
  850. ```
  851. ## Setting a row's height
  852. A row's height can be set using the following code:
  853. ``` php
  854. $spreadsheet->getActiveSheet()->getRowDimension('10')->setRowHeight(100);
  855. ```
  856. Excel measures row height in points, where 1 pt is 1/72 of an inch (or
  857. about 0.35mm). The default value is 12.75 pts; and the permitted range
  858. of values is between 0 and 409 pts, where 0 pts is a hidden row.
  859. ## Show/hide a row
  860. To set a worksheet''s row visibility, you can use the following code.
  861. The following example hides row number 10.
  862. ``` php
  863. $spreadsheet->getActiveSheet()->getRowDimension('10')->setVisible(false);
  864. ```
  865. Note that if you apply active filters using an AutoFilter, then this
  866. will override any rows that you hide or unhide manually within that
  867. AutoFilter range if you save the file.
  868. ## Group/outline a row
  869. To group/outline a row, you can use the following code:
  870. ``` php
  871. $spreadsheet->getActiveSheet()->getRowDimension('5')->setOutlineLevel(1);
  872. ```
  873. You can also collapse the row. Note that you should also set the row
  874. invisible, otherwise the collapse will not be visible in Excel 2007.
  875. ``` php
  876. $spreadsheet->getActiveSheet()->getRowDimension('5')->setCollapsed(true);
  877. $spreadsheet->getActiveSheet()->getRowDimension('5')->setVisible(false);
  878. ```
  879. Here's an example which collapses rows 50 to 80:
  880. ``` php
  881. for ($i = 51; $i <= 80; $i++) {
  882. $spreadsheet->getActiveSheet()->setCellValue('A' . $i, "FName $i");
  883. $spreadsheet->getActiveSheet()->setCellValue('B' . $i, "LName $i");
  884. $spreadsheet->getActiveSheet()->setCellValue('C' . $i, "PhoneNo $i");
  885. $spreadsheet->getActiveSheet()->setCellValue('D' . $i, "FaxNo $i");
  886. $spreadsheet->getActiveSheet()->setCellValue('E' . $i, true);
  887. $spreadsheet->getActiveSheet()->getRowDimension($i)->setOutlineLevel(1);
  888. $spreadsheet->getActiveSheet()->getRowDimension($i)->setVisible(false);
  889. }
  890. $spreadsheet->getActiveSheet()->getRowDimension(81)->setCollapsed(true);
  891. ```
  892. You can instruct PhpSpreadsheet to add a summary below the collapsible
  893. rows (default), or above. The following code adds the summary above:
  894. ``` php
  895. $spreadsheet->getActiveSheet()->setShowSummaryBelow(false);
  896. ```
  897. ## Merge/unmerge cells
  898. If you have a big piece of data you want to display in a worksheet, you
  899. can merge two or more cells together, to become one cell. This can be
  900. done using the following code:
  901. ``` php
  902. $spreadsheet->getActiveSheet()->mergeCells('A18:E22');
  903. ```
  904. Removing a merge can be done using the unmergeCells method:
  905. ``` php
  906. $spreadsheet->getActiveSheet()->unmergeCells('A18:E22');
  907. ```
  908. ## Inserting rows/columns
  909. You can insert/remove rows/columns at a specific position. The following
  910. code inserts 2 new rows, right before row 7:
  911. ``` php
  912. $spreadsheet->getActiveSheet()->insertNewRowBefore(7, 2);
  913. ```
  914. ## Add a drawing to a worksheet
  915. A drawing is always represented as a separate object, which can be added
  916. to a worksheet. Therefore, you must first instantiate a new
  917. `\PhpOffice\PhpSpreadsheet\Worksheet\Drawing`, and assign its properties a
  918. meaningful value:
  919. ``` php
  920. $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  921. $drawing->setName('Logo');
  922. $drawing->setDescription('Logo');
  923. $drawing->setPath('./images/officelogo.jpg');
  924. $drawing->setHeight(36);
  925. ```
  926. To add the above drawing to the worksheet, use the following snippet of
  927. code. PhpSpreadsheet creates the link between the drawing and the
  928. worksheet:
  929. ``` php
  930. $drawing->setWorksheet($spreadsheet->getActiveSheet());
  931. ```
  932. You can set numerous properties on a drawing, here are some examples:
  933. ``` php
  934. $drawing->setName('Paid');
  935. $drawing->setDescription('Paid');
  936. $drawing->setPath('./images/paid.png');
  937. $drawing->setCoordinates('B15');
  938. $drawing->setOffsetX(110);
  939. $drawing->setRotation(25);
  940. $drawing->getShadow()->setVisible(true);
  941. $drawing->getShadow()->setDirection(45);
  942. ```
  943. You can also add images created using GD functions without needing to
  944. save them to disk first as In-Memory drawings.
  945. ``` php
  946. // Use GD to create an in-memory image
  947. $gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream');
  948. $textColor = imagecolorallocate($gdImage, 255, 255, 255);
  949. imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor);
  950. // Add the In-Memory image to a worksheet
  951. $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();
  952. $drawing->setName('In-Memory image 1');
  953. $drawing->setDescription('In-Memory image 1');
  954. $drawing->setCoordinates('A1');
  955. $drawing->setImageResource($gdImage);
  956. $drawing->setRenderingFunction(
  957. \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG
  958. );
  959. $drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT);
  960. $drawing->setHeight(36);
  961. $drawing->setWorksheet($spreadsheet->getActiveSheet());
  962. ```
  963. ## Reading Images from a worksheet
  964. A commonly asked question is how to retrieve the images from a workbook
  965. that has been loaded, and save them as individual image files to disk.
  966. The following code extracts images from the current active worksheet,
  967. and writes each as a separate file.
  968. ``` php
  969. $i = 0;
  970. foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) {
  971. if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
  972. ob_start();
  973. call_user_func(
  974. $drawing->getRenderingFunction(),
  975. $drawing->getImageResource()
  976. );
  977. $imageContents = ob_get_contents();
  978. ob_end_clean();
  979. switch ($drawing->getMimeType()) {
  980. case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG :
  981. $extension = 'png';
  982. break;
  983. case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_GIF:
  984. $extension = 'gif';
  985. break;
  986. case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG :
  987. $extension = 'jpg';
  988. break;
  989. }
  990. } else {
  991. $zipReader = fopen($drawing->getPath(),'r');
  992. $imageContents = '';
  993. while (!feof($zipReader)) {
  994. $imageContents .= fread($zipReader,1024);
  995. }
  996. fclose($zipReader);
  997. $extension = $drawing->getExtension();
  998. }
  999. $myFileName = '00_Image_'.++$i.'.'.$extension;
  1000. file_put_contents($myFileName,$imageContents);
  1001. }
  1002. ```
  1003. ## Add rich text to a cell
  1004. Adding rich text to a cell can be done using
  1005. `\PhpOffice\PhpSpreadsheet\RichText\RichText` instances. Here''s an example, which
  1006. creates the following rich text string:
  1007. > This invoice is ***payable within thirty days after the end of the
  1008. > month*** unless specified otherwise on the invoice.
  1009. ``` php
  1010. $richText = new \PhpOffice\PhpSpreadsheet\RichText\RichText();
  1011. $richText->createText('This invoice is ');
  1012. $payable = $richText->createTextRun('payable within thirty days after the end of the month');
  1013. $payable->getFont()->setBold(true);
  1014. $payable->getFont()->setItalic(true);
  1015. $payable->getFont()->setColor( new \PhpOffice\PhpSpreadsheet\Style\Color( \PhpOffice\PhpSpreadsheet\Style\Color::COLOR_DARKGREEN ) );
  1016. $richText->createText(', unless specified otherwise on the invoice.');
  1017. $spreadsheet->getActiveSheet()->getCell('A18')->setValue($richText);
  1018. ```
  1019. ## Define a named range
  1020. PhpSpreadsheet supports the definition of named ranges. These can be
  1021. defined using the following code:
  1022. ``` php
  1023. // Add some data
  1024. $spreadsheet->setActiveSheetIndex(0);
  1025. $spreadsheet->getActiveSheet()->setCellValue('A1', 'Firstname:');
  1026. $spreadsheet->getActiveSheet()->setCellValue('A2', 'Lastname:');
  1027. $spreadsheet->getActiveSheet()->setCellValue('B1', 'Maarten');
  1028. $spreadsheet->getActiveSheet()->setCellValue('B2', 'Balliauw');
  1029. // Define named ranges
  1030. $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonFN', $spreadsheet->getActiveSheet(), 'B1') );
  1031. $spreadsheet->addNamedRange( new \PhpOffice\PhpSpreadsheet\NamedRange('PersonLN', $spreadsheet->getActiveSheet(), 'B2') );
  1032. ```
  1033. Optionally, a fourth parameter can be passed defining the named range
  1034. local (i.e. only usable on the current worksheet). Named ranges are
  1035. global by default.
  1036. ## Redirect output to a client's web browser
  1037. Sometimes, one really wants to output a file to a client''s browser,
  1038. especially when creating spreadsheets on-the-fly. There are some easy
  1039. steps that can be followed to do this:
  1040. 1. Create your PhpSpreadsheet spreadsheet
  1041. 2. Output HTTP headers for the type of document you wish to output
  1042. 3. Use the `\PhpOffice\PhpSpreadsheet\Writer\*` of your choice, and save
  1043. to `'php://output'`
  1044. `\PhpOffice\PhpSpreadsheet\Writer\Xlsx` uses temporary storage when
  1045. writing to `php://output`. By default, temporary files are stored in the
  1046. script's working directory. When there is no access, it falls back to
  1047. the operating system's temporary files location.
  1048. **This may not be safe for unauthorized viewing!** Depending on the
  1049. configuration of your operating system, temporary storage can be read by
  1050. anyone using the same temporary storage folder. When confidentiality of
  1051. your document is needed, it is recommended not to use `php://output`.
  1052. ### HTTP headers
  1053. Example of a script redirecting an Excel 2007 file to the client's
  1054. browser:
  1055. ``` php
  1056. /* Here there will be some code where you create $spreadsheet */
  1057. // redirect output to client browser
  1058. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1059. header('Content-Disposition: attachment;filename="myfile.xlsx"');
  1060. header('Cache-Control: max-age=0');
  1061. $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
  1062. $writer->save('php://output');
  1063. ```
  1064. Example of a script redirecting an Xls file to the client's browser:
  1065. ``` php
  1066. /* Here there will be some code where you create $spreadsheet */
  1067. // redirect output to client browser
  1068. header('Content-Type: application/vnd.ms-excel');
  1069. header('Content-Disposition: attachment;filename="myfile.xls"');
  1070. header('Cache-Control: max-age=0');
  1071. $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
  1072. $writer->save('php://output');
  1073. ```
  1074. **Caution:**
  1075. Make sure not to include any echo statements or output any other
  1076. contents than the Excel file. There should be no whitespace before the
  1077. opening `<?php` tag and at most one line break after the closing `?>`
  1078. tag (which can also be omitted to avoid problems). Make sure that your
  1079. script is saved without a BOM (Byte-order mark) because this counts as
  1080. echoing output. The same things apply to all included files. Failing to
  1081. follow the above guidelines may result in corrupt Excel files arriving
  1082. at the client browser, and/or that headers cannot be set by PHP
  1083. (resulting in warning messages).
  1084. ## Setting the default column width
  1085. Default column width can be set using the following code:
  1086. ``` php
  1087. $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);
  1088. ```
  1089. ## Setting the default row height
  1090. Default row height can be set using the following code:
  1091. ``` php
  1092. $spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
  1093. ```
  1094. ## Add a GD drawing to a worksheet
  1095. There might be a situation where you want to generate an in-memory image
  1096. using GD and add it to a `Spreadsheet` without first having to save this
  1097. file to a temporary location.
  1098. Here''s an example which generates an image in memory and adds it to the
  1099. active worksheet:
  1100. ``` php
  1101. // Generate an image
  1102. $gdImage = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream');
  1103. $textColor = imagecolorallocate($gdImage, 255, 255, 255);
  1104. imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor);
  1105. // Add a drawing to the worksheet
  1106. $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing();
  1107. $drawing->setName('Sample image');
  1108. $drawing->setDescription('Sample image');
  1109. $drawing->setImageResource($gdImage);
  1110. $drawing->setRenderingFunction(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::RENDERING_JPEG);
  1111. $drawing->setMimeType(\PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_DEFAULT);
  1112. $drawing->setHeight(36);
  1113. $drawing->setWorksheet($spreadsheet->getActiveSheet());
  1114. ```
  1115. ## Setting worksheet zoom level
  1116. To set a worksheet's zoom level, the following code can be used:
  1117. ``` php
  1118. $spreadsheet->getActiveSheet()->getSheetView()->setZoomScale(75);
  1119. ```
  1120. Note that zoom level should be in range 10 - 400.
  1121. ## Sheet tab color
  1122. Sometimes you want to set a color for sheet tab. For example you can
  1123. have a red sheet tab:
  1124. ``` php
  1125. $worksheet->getTabColor()->setRGB('FF0000');
  1126. ```
  1127. ## Creating worksheets in a workbook
  1128. If you need to create more worksheets in the workbook, here is how:
  1129. ``` php
  1130. $worksheet1 = $spreadsheet->createSheet();
  1131. $worksheet1->setTitle('Another sheet');
  1132. ```
  1133. Think of `createSheet()` as the "Insert sheet" button in Excel. When you
  1134. hit that button a new sheet is appended to the existing collection of
  1135. worksheets in the workbook.
  1136. ## Hidden worksheets (Sheet states)
  1137. Set a worksheet to be **hidden** using this code:
  1138. ``` php
  1139. $spreadsheet->getActiveSheet()
  1140. ->setSheetState(\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN);
  1141. ```
  1142. Sometimes you may even want the worksheet to be **"very hidden"**. The
  1143. available sheet states are :
  1144. - `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VISIBLE`
  1145. - `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_HIDDEN`
  1146. - `\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::SHEETSTATE_VERYHIDDEN`
  1147. In Excel the sheet state "very hidden" can only be set programmatically,
  1148. e.g. with Visual Basic Macro. It is not possible to make such a sheet
  1149. visible via the user interface.
  1150. ## Right-to-left worksheet
  1151. Worksheets can be set individually whether column `A` should start at
  1152. left or right side. Default is left. Here is how to set columns from
  1153. right-to-left.
  1154. ``` php
  1155. // right-to-left worksheet
  1156. $spreadsheet->getActiveSheet()->setRightToLeft(true);
  1157. ```