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.

accessing-cells.md 20 KiB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. # Accessing cells
  2. Accessing cells in a Spreadsheet should be pretty straightforward. This
  3. topic lists some of the options to access a cell.
  4. ## Setting a cell value by coordinate
  5. Setting a cell value by coordinate can be done using the worksheet's
  6. `setCellValue()` method.
  7. ``` php
  8. // Set cell A1 with a string value
  9. $spreadsheet->getActiveSheet()->setCellValue('A1', 'PhpSpreadsheet');
  10. // Set cell A2 with a numeric value
  11. $spreadsheet->getActiveSheet()->setCellValue('A2', 12345.6789);
  12. // Set cell A3 with a boolean value
  13. $spreadsheet->getActiveSheet()->setCellValue('A3', TRUE);
  14. // Set cell A4 with a formula
  15. $spreadsheet->getActiveSheet()->setCellValue(
  16. 'A4',
  17. '=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))'
  18. );
  19. ```
  20. Alternatively, you can retrieve the cell object, and then call the
  21. cell’s `setValue()` method:
  22. ``` php
  23. $spreadsheet->getActiveSheet()
  24. ->getCell('B8')
  25. ->setValue('Some value');
  26. ```
  27. ### Creating a new Cell
  28. If you make a call to `getCell()`, and the cell doesn't already exist, then
  29. PhpSpreadsheet will (by default) create the cell for you. If you don't want
  30. to create a new cell, then you can pass a second argument of false, and then
  31. `getCell()` will return a null if the cell doesn't exist.
  32. ### BEWARE: Cells assigned to variables as a Detached Reference
  33. As an "in-memory" model, PHPSpreadsheet can be very demanding of memory,
  34. particularly when working with large spreadsheets. One technique used to
  35. reduce this memory overhead is cell caching, so cells are actually
  36. maintained in a collection that may or may not be held in memory while you
  37. are working with the spreadsheet. Because of this, a call to `getCell()`
  38. (or any similar method) returns the cell data, and a pointer to the collection.
  39. While this is not normally an issue, it can become significant
  40. if you assign the result of a call to `getCell()` to a variable. Any
  41. subsequent calls to retrieve other cells will unset that pointer, although
  42. the cell object will still retain its data values.
  43. What does this mean? Consider the following code:
  44. ```
  45. $spreadSheet = new Spreadsheet();
  46. $workSheet = $spreadSheet->getActiveSheet();
  47. // Set details for the formula that we want to evaluate, together with any data on which it depends
  48. $workSheet->fromArray(
  49. [1, 2, 3],
  50. null,
  51. 'A1'
  52. );
  53. $cellC1 = $workSheet->getCell('C1');
  54. echo 'Value: ', $cellC1->getValue(), '; Address: ', $cellC1->getCoordinate(), PHP_EOL;
  55. $cellA1 = $workSheet->getCell('A1');
  56. echo 'Value: ', $cellA1->getValue(), '; Address: ', $cellA1->getCoordinate(), PHP_EOL;
  57. echo 'Value: ', $cellC1->getValue(), '; Address: ', $cellC1->getCoordinate(), PHP_EOL;
  58. ```
  59. The call to `getCell('C1')` returns the cell at `C1` containing its value (`3`),
  60. together with its link to the collection (used to identify its
  61. address/coordinate `C1`). The subsequent call to access cell `A1`
  62. modifies the value of `$cellC1`, detaching its link to the collection.
  63. So when we try to display the value and address a second time, we can display
  64. its value, but trying to display its address/coordinate will throw an
  65. exception because that link has been set to null.
  66. __Note:__ There are some internal methods that will fetch other cells from the
  67. collection, and this too will detach the link to the collection from any cell
  68. that you might have assigned to a variable.
  69. ## Excel DataTypes
  70. MS Excel supports 7 basic datatypes:
  71. - string
  72. - number
  73. - boolean
  74. - null
  75. - formula
  76. - error
  77. - Inline (or rich text) string
  78. By default, when you call the worksheet's `setCellValue()` method or the
  79. cell's `setValue()` method, PhpSpreadsheet will use the appropriate
  80. datatype for PHP nulls, booleans, floats or integers; or cast any string
  81. data value that you pass to the method into the most appropriate
  82. datatype, so numeric strings will be cast to numbers, while string
  83. values beginning with `=` will be converted to a formula. Strings that
  84. aren't numeric, or that don't begin with a leading `=` will be treated
  85. as genuine string values.
  86. This "conversion" is handled by a cell "value binder", and you can write
  87. custom "value binders" to change the behaviour of these "conversions".
  88. The standard PhpSpreadsheet package also provides an "advanced value
  89. binder" that handles a number of more complex conversions, such as
  90. converting strings with a fractional format like "3/4" to a number value
  91. (0.75 in this case) and setting an appropriate "fraction" number format
  92. mask. Similarly, strings like "5%" will be converted to a value of 0.05,
  93. and a percentage number format mask applied, and strings containing
  94. values that look like dates will be converted to Excel serialized
  95. datetimestamp values, and a corresponding mask applied. This is
  96. particularly useful when loading data from csv files, or setting cell
  97. values from a database.
  98. Formats handled by the advanced value binder include:
  99. - TRUE or FALSE (dependent on locale settings) are converted to booleans.
  100. - Numeric strings identified as scientific (exponential) format are
  101. converted to numbers.
  102. - Fractions and vulgar fractions are converted to numbers, and
  103. an appropriate number format mask applied.
  104. - Percentages are converted
  105. to numbers, divided by 100, and an appropriate number format mask
  106. applied.
  107. - Dates and times are converted to Excel timestamp values
  108. (numbers), and an appropriate number format mask applied.
  109. - When strings contain a newline character (`\n`), then the cell styling is
  110. set to wrap.
  111. You can read more about value binders later in this section of the
  112. documentation.
  113. ### Setting a formula in a Cell
  114. As stated above, if you store a string value with the first character an `=`
  115. in a cell. PHPSpreadsheet will treat that value as a formula, and then you
  116. can evaluate that formula by calling `getCalculatedValue()` against the cell.
  117. There may be times though, when you wish to store a value beginning with `=`
  118. as a string, and that you don't want PHPSpreadsheet to evaluate as though it
  119. was a formula.
  120. To do this, you need to "escape" the value by setting it as "quoted text".
  121. ```
  122. // Set cell A4 with a formula
  123. $spreadsheet->getActiveSheet()->setCellValue(
  124. 'A4',
  125. '=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))'
  126. );
  127. $spreadsheet->getActiveSheet()->getCell('A4')
  128. ->getStyle()->setQuotePrefix(true);
  129. ```
  130. Then, even if you ask PHPSpreadsheet to return the calculated value for cell
  131. `A4`, it will return `=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))`
  132. as a string, and not try to evaluate the formula.
  133. ### Setting a date and/or time value in a cell
  134. Date or time values are held as timestamp in Excel (a simple floating
  135. point value), and a number format mask is used to show how that value
  136. should be formatted; so if we want to store a date in a cell, we need to
  137. calculate the correct Excel timestamp, and set a number format mask.
  138. ``` php
  139. // Get the current date/time and convert to an Excel date/time
  140. $dateTimeNow = time();
  141. $excelDateValue = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel( $dateTimeNow );
  142. // Set cell A6 with the Excel date/time value
  143. $spreadsheet->getActiveSheet()->setCellValue(
  144. 'A6',
  145. $excelDateValue
  146. );
  147. // Set the number format mask so that the excel timestamp will be displayed as a human-readable date/time
  148. $spreadsheet->getActiveSheet()->getStyle('A6')
  149. ->getNumberFormat()
  150. ->setFormatCode(
  151. \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME
  152. );
  153. ```
  154. ### Setting a number with leading zeroes
  155. By default, PhpSpreadsheet will automatically detect the value type and
  156. set it to the appropriate Excel numeric datatype. This type conversion
  157. is handled by a value binder, as described in the section of this
  158. document entitled "Using value binders to facilitate data entry".
  159. Numbers don't have leading zeroes, so if you try to set a numeric value
  160. that does have leading zeroes (such as a telephone number) then these
  161. will be normally be lost as the value is cast to a number, so
  162. "01513789642" will be displayed as 1513789642.
  163. There are two ways you can force PhpSpreadsheet to override this
  164. behaviour.
  165. Firstly, you can set the datatype explicitly as a string so that it is
  166. not converted to a number.
  167. ``` php
  168. // Set cell A8 with a numeric value, but tell PhpSpreadsheet it should be treated as a string
  169. $spreadsheet->getActiveSheet()->setCellValueExplicit(
  170. 'A8',
  171. "01513789642",
  172. \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING
  173. );
  174. ```
  175. Alternatively, you can use a number format mask to display the value
  176. with leading zeroes.
  177. ``` php
  178. // Set cell A9 with a numeric value
  179. $spreadsheet->getActiveSheet()->setCellValue('A9', 1513789642);
  180. // Set a number format mask to display the value as 11 digits with leading zeroes
  181. $spreadsheet->getActiveSheet()->getStyle('A9')
  182. ->getNumberFormat()
  183. ->setFormatCode(
  184. '00000000000'
  185. );
  186. ```
  187. With number format masking, you can even break up the digits into groups
  188. to make the value more easily readable.
  189. ``` php
  190. // Set cell A10 with a numeric value
  191. $spreadsheet->getActiveSheet()->setCellValue('A10', 1513789642);
  192. // Set a number format mask to display the value as 11 digits with leading zeroes
  193. $spreadsheet->getActiveSheet()->getStyle('A10')
  194. ->getNumberFormat()
  195. ->setFormatCode(
  196. '0000-000-0000'
  197. );
  198. ```
  199. ![07-simple-example-1.png](./images/07-simple-example-1.png)
  200. **Note:** that not all complex format masks such as this one will work
  201. when retrieving a formatted value to display "on screen", or for certain
  202. writers such as HTML or PDF, but it will work with the true spreadsheet
  203. writers (Xlsx and Xls).
  204. ## Setting a range of cells from an array
  205. It is also possible to set a range of cell values in a single call by
  206. passing an array of values to the `fromArray()` method.
  207. ``` php
  208. $arrayData = [
  209. [NULL, 2010, 2011, 2012],
  210. ['Q1', 12, 15, 21],
  211. ['Q2', 56, 73, 86],
  212. ['Q3', 52, 61, 69],
  213. ['Q4', 30, 32, 0],
  214. ];
  215. $spreadsheet->getActiveSheet()
  216. ->fromArray(
  217. $arrayData, // The data to set
  218. NULL, // Array values with this value will not be set
  219. 'C3' // Top left coordinate of the worksheet range where
  220. // we want to set these values (default is A1)
  221. );
  222. ```
  223. ![07-simple-example-2.png](./images/07-simple-example-2.png)
  224. If you pass a 2-d array, then this will be treated as a series of rows
  225. and columns. A 1-d array will be treated as a single row, which is
  226. particularly useful if you're fetching an array of data from a database.
  227. ``` php
  228. $rowArray = ['Value1', 'Value2', 'Value3', 'Value4'];
  229. $spreadsheet->getActiveSheet()
  230. ->fromArray(
  231. $rowArray, // The data to set
  232. NULL, // Array values with this value will not be set
  233. 'C3' // Top left coordinate of the worksheet range where
  234. // we want to set these values (default is A1)
  235. );
  236. ```
  237. ![07-simple-example-3.png](./images/07-simple-example-3.png)
  238. If you have a simple 1-d array, and want to write it as a column, then
  239. the following will convert it into an appropriately structured 2-d array
  240. that can be fed to the `fromArray()` method:
  241. ``` php
  242. $rowArray = ['Value1', 'Value2', 'Value3', 'Value4'];
  243. $columnArray = array_chunk($rowArray, 1);
  244. $spreadsheet->getActiveSheet()
  245. ->fromArray(
  246. $columnArray, // The data to set
  247. NULL, // Array values with this value will not be set
  248. 'C3' // Top left coordinate of the worksheet range where
  249. // we want to set these values (default is A1)
  250. );
  251. ```
  252. ![07-simple-example-4.png](./images/07-simple-example-4.png)
  253. ## Retrieving a cell value by coordinate
  254. To retrieve the value of a cell, the cell should first be retrieved from
  255. the worksheet using the `getCell()` method. A cell's value can be read
  256. using the `getValue()` method.
  257. ``` php
  258. // Get the value from cell A1
  259. $cellValue = $spreadsheet->getActiveSheet()->getCell('A1')->getValue();
  260. ```
  261. This will retrieve the raw, unformatted value contained in the cell.
  262. If a cell contains a formula, and you need to retrieve the calculated
  263. value rather than the formula itself, then use the cell's
  264. `getCalculatedValue()` method. This is further explained in
  265. [the calculation engine](./calculation-engine.md).
  266. ``` php
  267. // Get the value from cell A4
  268. $cellValue = $spreadsheet->getActiveSheet()->getCell('A4')->getCalculatedValue();
  269. ```
  270. Alternatively, if you want to see the value with any cell formatting
  271. applied (e.g. for a human-readable date or time value), then you can use
  272. the cell's `getFormattedValue()` method.
  273. ``` php
  274. // Get the value from cell A6
  275. $cellValue = $spreadsheet->getActiveSheet()->getCell('A6')->getFormattedValue();
  276. ```
  277. ## Setting a cell value by column and row
  278. Setting a cell value by coordinate can be done using the worksheet's
  279. `setCellValueByColumnAndRow()` method.
  280. ``` php
  281. // Set cell A5 with a string value
  282. $spreadsheet->getActiveSheet()->setCellValueByColumnAndRow(1, 5, 'PhpSpreadsheet');
  283. ```
  284. **Note:** that column references start with `1` for column `A`.
  285. ## Retrieving a cell value by column and row
  286. To retrieve the value of a cell, the cell should first be retrieved from
  287. the worksheet using the `getCellByColumnAndRow()` method. A cell’s value can
  288. be read again using the following line of code:
  289. ``` php
  290. // Get the value from cell B5
  291. $cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(2, 5)->getValue();
  292. ```
  293. If you need the calculated value of a cell, use the following code. This
  294. is further explained in [the calculation engine](./calculation-engine.md).
  295. ``` php
  296. // Get the value from cell A4
  297. $cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(1, 4)->getCalculatedValue();
  298. ```
  299. ## Retrieving a range of cell values to an array
  300. It is also possible to retrieve a range of cell values to an array in a
  301. single call using the `toArray()`, `rangeToArray()` or
  302. `namedRangeToArray()` methods.
  303. ``` php
  304. $dataArray = $spreadsheet->getActiveSheet()
  305. ->rangeToArray(
  306. 'C3:E5', // The worksheet range that we want to retrieve
  307. NULL, // Value that should be returned for empty cells
  308. TRUE, // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell)
  309. TRUE, // Should values be formatted (the equivalent of getFormattedValue() for each cell)
  310. TRUE // Should the array be indexed by cell row and cell column
  311. );
  312. ```
  313. These methods will all return a 2-d array of rows and columns. The
  314. `toArray()` method will return the whole worksheet; `rangeToArray()`
  315. will return a specified range or cells; while `namedRangeToArray()` will
  316. return the cells within a defined `named range`.
  317. ## Looping through cells
  318. ### Looping through cells using iterators
  319. The easiest way to loop cells is by using iterators. Using iterators,
  320. one can use foreach to loop worksheets, rows within a worksheet, and
  321. cells within a row.
  322. Below is an example where we read all the values in a worksheet and
  323. display them in a table.
  324. ``` php
  325. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
  326. $reader->setReadDataOnly(TRUE);
  327. $spreadsheet = $reader->load("test.xlsx");
  328. $worksheet = $spreadsheet->getActiveSheet();
  329. echo '<table>' . PHP_EOL;
  330. foreach ($worksheet->getRowIterator() as $row) {
  331. echo '<tr>' . PHP_EOL;
  332. $cellIterator = $row->getCellIterator();
  333. $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
  334. // even if a cell value is not set.
  335. // By default, only cells that have a value
  336. // set will be iterated.
  337. foreach ($cellIterator as $cell) {
  338. echo '<td>' .
  339. $cell->getValue() .
  340. '</td>' . PHP_EOL;
  341. }
  342. echo '</tr>' . PHP_EOL;
  343. }
  344. echo '</table>' . PHP_EOL;
  345. ```
  346. Note that we have set the cell iterator's
  347. `setIterateOnlyExistingCells()` to FALSE. This makes the iterator loop
  348. all cells within the worksheet range, even if they have not been set.
  349. The cell iterator will return a `null` as the cell value if it is not
  350. set in the worksheet. Setting the cell iterator's
  351. `setIterateOnlyExistingCells()` to `false` will loop all cells in the
  352. worksheet that can be available at that moment. This will create new
  353. cells if required and increase memory usage! Only use it if it is
  354. intended to loop all cells that are possibly available.
  355. ### Looping through cells using indexes
  356. One can use the possibility to access cell values by column and row
  357. index like `[1, 1]` instead of `'A1'` for reading and writing cell values in
  358. loops.
  359. **Note:** In PhpSpreadsheet column index and row index are 1-based. That means `'A1'` ~ `[1, 1]`
  360. Below is an example where we read all the values in a worksheet and
  361. display them in a table.
  362. ``` php
  363. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
  364. $reader->setReadDataOnly(TRUE);
  365. $spreadsheet = $reader->load("test.xlsx");
  366. $worksheet = $spreadsheet->getActiveSheet();
  367. // Get the highest row and column numbers referenced in the worksheet
  368. $highestRow = $worksheet->getHighestRow(); // e.g. 10
  369. $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
  370. $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5
  371. echo '<table>' . "\n";
  372. for ($row = 1; $row <= $highestRow; ++$row) {
  373. echo '<tr>' . PHP_EOL;
  374. for ($col = 1; $col <= $highestColumnIndex; ++$col) {
  375. $value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
  376. echo '<td>' . $value . '</td>' . PHP_EOL;
  377. }
  378. echo '</tr>' . PHP_EOL;
  379. }
  380. echo '</table>' . PHP_EOL;
  381. ```
  382. Alternatively, you can take advantage of PHP's "Perl-style" character
  383. incrementors to loop through the cells by coordinate:
  384. ``` php
  385. $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
  386. $reader->setReadDataOnly(TRUE);
  387. $spreadsheet = $reader->load("test.xlsx");
  388. $worksheet = $spreadsheet->getActiveSheet();
  389. // Get the highest row number and column letter referenced in the worksheet
  390. $highestRow = $worksheet->getHighestRow(); // e.g. 10
  391. $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
  392. // Increment the highest column letter
  393. $highestColumn++;
  394. echo '<table>' . "\n";
  395. for ($row = 1; $row <= $highestRow; ++$row) {
  396. echo '<tr>' . PHP_EOL;
  397. for ($col = 'A'; $col != $highestColumn; ++$col) {
  398. echo '<td>' .
  399. $worksheet->getCell($col . $row)
  400. ->getValue() .
  401. '</td>' . PHP_EOL;
  402. }
  403. echo '</tr>' . PHP_EOL;
  404. }
  405. echo '</table>' . PHP_EOL;
  406. ```
  407. Note that we can't use a `<=` comparison here, because `'AA'` would match
  408. as `<= 'B'`, so we increment the highest column letter and then loop
  409. while `$col !=` the incremented highest column.
  410. ## Using value binders to facilitate data entry
  411. Internally, PhpSpreadsheet uses a default
  412. `\PhpOffice\PhpSpreadsheet\Cell\IValueBinder` implementation
  413. (\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder) to determine data
  414. types of entered data using a cell's `setValue()` method (the
  415. `setValueExplicit()` method bypasses this check).
  416. Optionally, the default behaviour of PhpSpreadsheet can be modified,
  417. allowing easier data entry. For example, a
  418. `\PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder` class is available.
  419. It automatically converts percentages, number in scientific format, and
  420. dates entered as strings to the correct format, also setting the cell's
  421. style information. The following example demonstrates how to set the
  422. value binder in PhpSpreadsheet:
  423. ``` php
  424. /** PhpSpreadsheet */
  425. require_once 'src/Boostrap.php';
  426. // Set value binder
  427. \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );
  428. // Create new Spreadsheet object
  429. $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  430. // ...
  431. // Add some data, resembling some different data types
  432. $spreadsheet->getActiveSheet()->setCellValue('A4', 'Percentage value:');
  433. // Converts the string value to 0.1 and sets percentage cell style
  434. $spreadsheet->getActiveSheet()->setCellValue('B4', '10%');
  435. $spreadsheet->getActiveSheet()->setCellValue('A5', 'Date/time value:');
  436. // Converts the string value to an Excel datestamp and sets the date format cell style
  437. $spreadsheet->getActiveSheet()->setCellValue('B5', '21 December 1983');
  438. ```
  439. **Creating your own value binder is easy.** When advanced value binding
  440. is required, you can implement the
  441. `\PhpOffice\PhpSpreadsheet\Cell\IValueBinder` interface or extend the
  442. `\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder` or
  443. `\PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder` classes.