For God so loved the world, that He gave His only begotten Son, that all who believe in Him should not perish but have everlasting life
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.

390 lines
17 KiB

  1. # PHPExcel Developer Documentation
  2. ## Accessing cells
  3. Accessing cells in a PHPExcel worksheet should be pretty straightforward. This 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 `setCellValue()` method.
  6. ```php
  7. // Set cell A1 with a string value
  8. $objPHPExcel->getActiveSheet()->setCellValue('A1', 'PHPExcel');
  9. // Set cell A2 with a numeric value
  10. $objPHPExcel->getActiveSheet()->setCellValue('A2', 12345.6789);
  11. // Set cell A3 with a boolean value
  12. $objPHPExcel->getActiveSheet()->setCellValue('A3', TRUE);
  13. // Set cell A4 with a formula
  14. $objPHPExcel->getActiveSheet()->setCellValue(
  15. 'A4',
  16. '=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))'
  17. );
  18. ```
  19. Alternatively, you can retrieve the cell object, and then call the cell’s setValue() method:
  20. ```php
  21. $objPHPExcel->getActiveSheet()
  22. ->getCell('B8')
  23. ->setValue('Some value');
  24. ```
  25. **Excel DataTypes**
  26. MS Excel supports 7 basic datatypes
  27. - string
  28. - number
  29. - boolean
  30. - null
  31. - formula
  32. - error
  33. - Inline (or rich text) string
  34. By default, when you call the worksheet's `setCellValue()` method or the cell's `setValue()` method, PHPExcel will use the appropriate datatype for PHP nulls, booleans, floats or integers; or cast any string data value that you pass to the method into the most appropriate datatype, so numeric strings will be cast to numbers, while string values beginning with “=” will be converted to a formula. Strings that aren't numeric, or that don't begin with a leading "=" will be treated as genuine string values.
  35. This "conversion" is handled by a cell "value binder", and you can write custom "value binders" to change the behaviour of these "conversions". The standard PHPExcel package also provides an "advanced value binder" that handles a number of more complex conversions, such as converting strings with a fractional format like "3/4" to a number value (0.75 in this case) and setting an appropriate "fraction" number format mask. Similarly, strings like "5%" will be converted to a value of 0.05, and a percentage number format mask applied, and strings containing values that look like dates will be converted to Excel serialized datetimestamp values, and a corresponding mask applied. This is particularly useful when loading data from csv files, or setting cell values from a database.
  36. Formats handled by the advanced value binder include
  37. - TRUE or FALSE (dependent on locale settings) are converted to booleans.
  38. - Numeric strings identified as scientific (exponential) format are converted to numbers.
  39. - Fractions and vulgar fractions are converted to numbers, and an appropriate number format mask applied.
  40. - Percentages are converted to numbers, divided by 100, and an appropriate number format mask applied.
  41. - Dates and times are converted to Excel timestamp values (numbers), and an appropriate number format mask applied.
  42. - When strings contain a newline character ("\n"), then the cell styling is set to wrap.
  43. You can read more about value binders later in this section of the documentation.
  44. #### Setting a date and/or time value in a cell
  45. Date or time values are held as timestamp in Excel (a simple floating point value), and a number format mask is used to show how that value should be formatted; so if we want to store a date in a cell, we need to calculate the correct Excel timestamp, and set a number format mask.
  46. ```php
  47. // Get the current date/time and convert to an Excel date/time
  48. $dateTimeNow = time();
  49. $excelDateValue = PHPExcel_Shared_Date::PHPToExcel( $dateTimeNow );
  50. // Set cell A6 with the Excel date/time value
  51. $objPHPExcel->getActiveSheet()->setCellValue(
  52. 'A6',
  53. $excelDateValue
  54. );
  55. // Set the number format mask so that the excel timestamp will be displayed as a human-readable date/time
  56. $objPHPExcel->getActiveSheet()->getStyle('A6')
  57. ->getNumberFormat()
  58. ->setFormatCode(
  59. PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME
  60. );
  61. ```
  62. #### Setting a number with leading zeroes
  63. By default, PHPExcel will automatically detect the value type and set it to the appropriate Excel numeric datatype. This type conversion is handled by a value binder, as described in the section of this document entitled "Using value binders to facilitate data entry".
  64. Numbers don't have leading zeroes, so if you try to set a numeric value that does have leading zeroes (such as a telephone number) then these will be normally be lost as the value is cast to a number, so "01513789642" will be displayed as 1513789642.
  65. There are two ways you can force PHPExcel to override this behaviour.
  66. Firstly, you can set the datatype explicitly as a string so that it is not converted to a number.
  67. ```php
  68. // Set cell A8 with a numeric value, but tell PHPExcel it should be treated as a string
  69. $objPHPExcel->getActiveSheet()->setCellValueExplicit(
  70. 'A8',
  71. "01513789642",
  72. PHPExcel_Cell_DataType::TYPE_STRING
  73. );
  74. ```
  75. Alternatively, you can use a number format mask to display the value with leading zeroes.
  76. ```php
  77. // Set cell A9 with a numeric value
  78. $objPHPExcel->getActiveSheet()->setCellValue('A9', 1513789642);
  79. // Set a number format mask to display the value as 11 digits with leading zeroes
  80. $objPHPExcel->getActiveSheet()->getStyle('A9')
  81. ->getNumberFormat()
  82. ->setFormatCode(
  83. '00000000000'
  84. );
  85. ```
  86. With number format masking, you can even break up the digits into groups to make the value more easily readable.
  87. ```php
  88. // Set cell A10 with a numeric value
  89. $objPHPExcel->getActiveSheet()->setCellValue('A10', 1513789642);
  90. // Set a number format mask to display the value as 11 digits with leading zeroes
  91. $objPHPExcel->getActiveSheet()->getStyle('A10')
  92. ->getNumberFormat()
  93. ->setFormatCode(
  94. '0000-000-0000'
  95. );
  96. ```
  97. ![07-simple-example-1.png](./images/07-simple-example-1.png "")
  98. **Note** that not all complex format masks such as this one will work when retrieving a formatted value to display "on screen", or for certain writers such as HTML or PDF, but it will work with the true spreadsheet writers (Excel2007 and Excel5).
  99. ### Setting a range of cells from an array
  100. It is also possible to set a range of cell values in a single call by passing an array of values to the `fromArray()` method.
  101. ```php
  102. $arrayData = array(
  103. array(NULL, 2010, 2011, 2012),
  104. array('Q1', 12, 15, 21),
  105. array('Q2', 56, 73, 86),
  106. array('Q3', 52, 61, 69),
  107. array('Q4', 30, 32, 0),
  108. );
  109. $objPHPExcel->getActiveSheet()
  110. ->fromArray(
  111. $arrayData, // The data to set
  112. NULL, // Array values with this value will not be set
  113. 'C3' // Top left coordinate of the worksheet range where
  114. // we want to set these values (default is A1)
  115. );
  116. ```
  117. ![07-simple-example-2.png](./images/07-simple-example-2.png "")
  118. If you pass a 2-d array, then this will be treated as a series of rows and columns. A 1-d array will be treated as a single row, which is particularly useful if you're fetching an array of data from a database.
  119. ```php
  120. $rowArray = array('Value1', 'Value2', 'Value3', 'Value4');
  121. $objPHPExcel->getActiveSheet()
  122. ->fromArray(
  123. $rowArray, // The data to set
  124. NULL, // Array values with this value will not be set
  125. 'C3' // Top left coordinate of the worksheet range where
  126. // we want to set these values (default is A1)
  127. );
  128. ```
  129. ![07-simple-example-3.png](./images/07-simple-example-3.png "")
  130. If you have a simple 1-d array, and want to write it as a column, then the following will convert it into an appropriately structured 2-d array that can be fed to the `fromArray()` method:
  131. ```php
  132. $rowArray = array('Value1', 'Value2', 'Value3', 'Value4');
  133. $columnArray = array_chunk($rowArray, 1);
  134. $objPHPExcel->getActiveSheet()
  135. ->fromArray(
  136. $columnArray, // The data to set
  137. NULL, // Array values with this value will not be set
  138. 'C3' // Top left coordinate of the worksheet range where
  139. // we want to set these values (default is A1)
  140. );
  141. ```
  142. ![07-simple-example-4.png](./images/07-simple-example-4.png "")
  143. ### Retrieving a cell value by coordinate
  144. To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the `getCell()` method. A cell's value can be read using the `getValue()` method.
  145. ```php
  146. // Get the value fom cell A1
  147. $cellValue = $objPHPExcel->getActiveSheet()->getCell('A1')
  148. ->getValue();
  149. ```
  150. This will retrieve the raw, unformatted value contained in the cell.
  151. If a cell contains a formula, and you need to retrieve the calculated value rather than the formula itself, then use the cell's `getCalculatedValue()` method. This is further explained in .
  152. ```php
  153. // Get the value fom cell A4
  154. $cellValue = $objPHPExcel->getActiveSheet()->getCell('A4')
  155. ->getCalculatedValue();
  156. ```
  157. Alternatively, if you want to see the value with any cell formatting applied (e.g. for a human-readable date or time value), then you can use the cell's `getFormattedValue()` method.
  158. ```php
  159. // Get the value fom cell A6
  160. $cellValue = $objPHPExcel->getActiveSheet()->getCell('A6')
  161. ->getFormattedValue();
  162. ```
  163. ### Setting a cell value by column and row
  164. Setting a cell value by coordinate can be done using the worksheet's `setCellValueByColumnAndRow()` method.
  165. ```php
  166. // Set cell B5 with a string value
  167. $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, 5, 'PHPExcel');
  168. ```
  169. **Note** that column references start with '0' for column 'A', rather than from '1'.
  170. ### Retrieving a cell value by column and row
  171. To retrieve the value of a cell, the cell should first be retrieved from the worksheet using the getCellByColumnAndRow method. A cell’s value can be read again using the following line of code:
  172. ```php
  173. // Get the value fom cell B5
  174. $cellValue = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow(1, 5)
  175. ->getValue();
  176. ```
  177. If you need the calculated value of a cell, use the following code. This is further explained in .
  178. ```php
  179. // Get the value fom cell A4
  180. $cellValue = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow(0, 4)
  181. ->getCalculatedValue();
  182. ```
  183. ### Retrieving a range of cell values to an array
  184. It is also possible to retrieve a range of cell values to an array in a single call using the `toArray()`, `rangeToArray()` or `namedRangeToArray()` methods.
  185. ```php
  186. $dataArray = $objPHPExcel->getActiveSheet()
  187. ->rangeToArray(
  188. 'C3:E5', // The worksheet range that we want to retrieve
  189. NULL, // Value that should be returned for empty cells
  190. TRUE, // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell)
  191. TRUE, // Should values be formatted (the equivalent of getFormattedValue() for each cell)
  192. TRUE // Should the array be indexed by cell row and cell column
  193. );
  194. ```
  195. These methods will all return a 2-d array of rows and columns. The `toArray()` method will return the whole worksheet; `rangeToArray()` will return a specified range or cells; while `namedRangeToArray()` will return the cells within a defined `named range`.
  196. ### Looping through cells
  197. #### Looping through cells using iterators
  198. The easiest way to loop cells is by using iterators. Using iterators, one can use foreach to loop worksheets, rows within a worksheet, and cells within a row.
  199. Below is an example where we read all the values in a worksheet and display them in a table.
  200. ```php
  201. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  202. $objReader->setReadDataOnly(TRUE);
  203. $objPHPExcel = $objReader->load("test.xlsx");
  204. $objWorksheet = $objPHPExcel->getActiveSheet();
  205. echo '<table>' . PHP_EOL;
  206. foreach ($objWorksheet->getRowIterator() as $row) {
  207. echo '<tr>' . PHP_EOL;
  208. $cellIterator = $row->getCellIterator();
  209. $cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
  210. // even if a cell value is not set.
  211. // By default, only cells that have a value
  212. // set will be iterated.
  213. foreach ($cellIterator as $cell) {
  214. echo '<td>' .
  215. $cell->getValue() .
  216. '</td>' . PHP_EOL;
  217. }
  218. echo '</tr>' . PHP_EOL;
  219. }
  220. echo '</table>' . PHP_EOL;
  221. ```
  222. Note that we have set the cell iterator's `setIterateOnlyExistingCells()` to FALSE. This makes the iterator loop all cells within the worksheet range, even if they have not been set.
  223. The cell iterator will return a __NULL__ as the cell value if it is not set in the worksheet.
  224. Setting the cell iterator's setIterateOnlyExistingCells() to FALSE will loop all cells in the worksheet that can be available at that moment. This will create new cells if required and increase memory usage! Only use it if it is intended to loop all cells that are possibly available.
  225. #### Looping through cells using indexes
  226. One can use the possibility to access cell values by column and row index like (0,1) instead of 'A1' for reading and writing cell values in loops.
  227. Note: In PHPExcel column index is 0-based while row index is 1-based. That means 'A1' ~ (0,1)
  228. Below is an example where we read all the values in a worksheet and display them in a table.
  229. ```php
  230. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  231. $objReader->setReadDataOnly(TRUE);
  232. $objPHPExcel = $objReader->load("test.xlsx");
  233. $objWorksheet = $objPHPExcel->getActiveSheet();
  234. // Get the highest row and column numbers referenced in the worksheet
  235. $highestRow = $objWorksheet->getHighestRow(); // e.g. 10
  236. $highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
  237. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
  238. echo '<table>' . "\n";
  239. for ($row = 1; $row <= $highestRow; ++$row) {
  240. echo '<tr>' . PHP_EOL;
  241. for ($col = 0; $col <= $highestColumnIndex; ++$col) {
  242. echo '<td>' .
  243. $objWorksheet->getCellByColumnAndRow($col, $row)
  244. ->getValue() .
  245. '</td>' . PHP_EOL;
  246. }
  247. echo '</tr>' . PHP_EOL;
  248. }
  249. echo '</table>' . PHP_EOL;
  250. ```
  251. Alternatively, you can take advantage of PHP's "Perl-style" character incrementors to loop through the cells by coordinate:
  252. ```php
  253. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  254. $objReader->setReadDataOnly(TRUE);
  255. $objPHPExcel = $objReader->load("test.xlsx");
  256. $objWorksheet = $objPHPExcel->getActiveSheet();
  257. // Get the highest row number and column letter referenced in the worksheet
  258. $highestRow = $objWorksheet->getHighestRow(); // e.g. 10
  259. $highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
  260. // Increment the highest column letter
  261. $highestColumn++;
  262. echo '<table>' . "\n";
  263. for ($row = 1; $row <= $highestRow; ++$row) {
  264. echo '<tr>' . PHP_EOL;
  265. for ($col = 'A'; $col != $highestColumn; ++$col) {
  266. echo '<td>' .
  267. $objWorksheet->getCell($col . $row)
  268. ->getValue() .
  269. '</td>' . PHP_EOL;
  270. }
  271. echo '</tr>' . PHP_EOL;
  272. }
  273. echo '</table>' . PHP_EOL;
  274. ```
  275. Note that we can't use a <= comparison here, because 'AA' would match as <= 'B', so we increment the highest column letter and then loop while $col != the incremented highest column.
  276. ### Using value binders to facilitate data entry
  277. Internally, PHPExcel uses a default PHPExcel_Cell_IValueBinder implementation (PHPExcel_Cell_DefaultValueBinder) to determine data types of entered data using a cell's `setValue()` method (the `setValueExplicit()` method bypasses this check).
  278. Optionally, the default behaviour of PHPExcel can be modified, allowing easier data entry. For example, a PHPExcel_Cell_AdvancedValueBinder class is available. It automatically converts percentages, number in scientific format, and dates entered as strings to the correct format, also setting the cell's style information. The following example demonstrates how to set the value binder in PHPExcel:
  279. ```php
  280. /** PHPExcel */
  281. require_once 'PHPExcel.php';
  282. // Set value binder
  283. PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
  284. // Create new PHPExcel object
  285. $objPHPExcel = new PHPExcel();
  286. // ...
  287. // Add some data, resembling some different data types
  288. $objPHPExcel->getActiveSheet()->setCellValue('A4', 'Percentage value:');
  289. // Converts the string value to 0.1 and sets percentage cell style
  290. $objPHPExcel->getActiveSheet()->setCellValue('B4', '10%');
  291. $objPHPExcel->getActiveSheet()->setCellValue('A5', 'Date/time value:');
  292. // Converts the string value to an Excel datestamp and sets the date format cell style
  293. $objPHPExcel->getActiveSheet()->setCellValue('B5', '21 December 1983');
  294. ```
  295. __Creating your own value binder is easy.__
  296. When advanced value binding is required, you can implement the PHPExcel_Cell_IValueBinder interface or extend the PHPExcel_Cell_DefaultValueBinder or PHPExcel_Cell_AdvancedValueBinder classes.