Accessing cells

Accessing cells in a Spreadsheet should be pretty straightforward. This topic lists some of the options to access a cell.

Place setting a cell value by coordinate

Setting a cellphone value by organize can be done victimization the worksheet's setCellValue() method.

          // Set cell A1 with a twine time value $spreadsheet->getActiveSheet()->setCellValue('A1', 'PhpSpreadsheet');  // Localise cellphone A2 with a numeric value $spreadsheet->getActiveSheet()->setCellValue('A2', 12345.6789);  // Set cell A3 with a boolean esteem $spreadsheet->getActiveSheet()->setCellValue('A3', TRUE);  // Set cell A4 with a formula $spreadsheet->getActiveSheet()->setCellValue(     'A4',     '=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))' );                  

Alternatively, you can retrieve the cell physical object, and then call the cell's setValue() method:

          $spreadsheet->getActiveSheet()     ->getCell('B8')     ->setValue('Some value');                  

Creating a new Cell

If you cook a call to getCell(), and the prison cell doesn't already exist, then PhpSpreadsheet leave (by default) create the electric cell for you. If you don't want to create a new cell, past you can pass around a s argument of false, and then getCell() will devolve a null if the cell doesn't exist.

Mind: Cells assigned to variables as a Freestanding Reference

As an "in-computer storage" model, PHPSpreadsheet can be very demanding of memory, particularly when working with large spreadsheets. Matchless technique accustomed reduce this memory overhead is cell caching, sol cells are in reality maintained in a collection that may or may not personify held in store piece you are working with the spreadsheet. Because of this, a call to getCell() (or any confusable method) returns the electric cell information, and a pointer to the collection. While this is non ordinarily an effect, it fire get ahead significant if you specify the result of a call in to getCell() to a variable. Any subsequent calls to retrieve other cells will unset that pointer, although the cell object leave still retain its data values.

What does this mean? Consider the following encode:

          $spreadSheet = new Spreadsheet(); $workSheet = $spreadSheet->getActiveSheet();  // Place details for the chemical formula that we want to evaluate, together with any data on which it depends $workSheet->fromArray(     [1, 2, 3],     null,     'A1' );  $cellC1 = $workSheet->getCell('C1'); echo 'Note value: ', $cellC1->getValue(), '; Address: ', $cellC1->getCoordinate(), PHP_EOL;  $cellA1 = $workSheet->getCell('A1'); echo 'Value: ', $cellA1->getValue(), '; Address: ', $cellA1->getCoordinate(), PHP_EOL;  echo 'Value: ', $cellC1->getValue(), '; Address: ', $cellC1->getCoordinate(), PHP_EOL;                  

The call to getCell('C1') returns the cellular telephone at C1 containing its apprais (3), together with its link to the collection (wont to identify its come up to/coordinate C1). The subsequent cry to access cell A1 modifies the apprais of $cellC1, detaching its yoke to the collection.

And so when we try to display the valuate and address a second time, we can display its value, but trying to exhibit its treat/coordinate will give an exception because that link has been set to null.

Billet: There are some internal methods that testament fetch other cells from the collection, and this too volition detach the link to the collection from any cell that you mightiness stimulate assigned to a variable.

Excel DataTypes

MS Excel supports 7 alkaline datatypes:

  • string
  • number
  • mathematician
  • null
  • pattern
  • error
  • Inline (or fat text) bowed stringed instrument

By default, when you call the worksheet's setCellValue() method or the cell's setValue() method, PhpSpreadsheet bequeath use the appropriate datatype for PHP nulls, booleans, floats or integers; or cast whatever string data value that you pass to the method acting into the most appropriate datatype, so numeric strings will constitute cast to numbers game, while chain values starting time with = volition be converted to a formula. Strings that aren't quantitative, or that wear't begin with a leading = will be treated As genuine string values.

Note that a numeral string that begins with a leading goose egg (that isn't immediately followed by a decimal separator) will not be reborn to a numeric, so values like phone Book of Numbers (e.g. `01615991375``will rest as strings).

This "conversion" is handled by a cadre "value binder", and you can write custom "treasure binders" to transfer the demeanor of these "conversions". The standard PhpSpreadsheet package also provides an "advanced measure binder" that handles a number of to a greater extent complex conversions, such arsenic converting strings with a fractional format like "3/4" to a number value (0.75 in that case) and setting an appropriate "divide" number format mask. Likewise, strings suchlike "5%" bequeath 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 masquerade party applied. This is particularly useful when lading data from csv files, or setting cubicle values from a database.

Formats handled by the advanced respect binder include:

  • TRUE or FALSE (dependant on locale settings) are converted to booleans.
  • Numeral strings identified as technological (exponential) format are converted to numbers.
  • Fractions and vulgar fractions are converted to numbers, and an appropriate turn format mask practical.
  • Percentages are converted to numbers, divided past 100, and an appropriate telephone number initialise mask applied.
  • Dates and multiplication are regenerate to Excel timestamp values (numbers), and an appropriate number initialize masqu applied.
  • When strings arrest a newline type (\n), then the cell styling is sic to wrap.

Basically, it attempts to mimic the demeanor of the Manuscript Excel GUI.

You can read more about value binders tardive in this section of the software documentation.

Setting a formula in a Cell

As stated above, if you store a drawing string value with the beginning character an = in a jail cell. PHPSpreadsheet will treat that value as a normal, and so you can judge that formula by calling getCalculatedValue() against the cell.

At that place English hawthorn be times though, when you bid to memory boar a value starting time with = as a drawing string, and that you don't want PHPSpreadsheet to evaluate as though it was a expression.

To do this, you need to "break away" the value aside scope it as "quoted text".

          // Set cell A4 with a formula $spreadsheet->getActiveSheet()->setCellValue(     'A4',     '=IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1))' ); $spreadsheet->getActiveSheet()->getCell('A4')     ->getStyle()->setQuotePrefix(true);                  

Then, even if you ask PHPSpreadsheet to return the deliberate value for cell A4, it will return =IF(A3, CONCATENATE(A1, " ", A2), CONCATENATE(A2, " ", A1)) as a string, and not try to evaluate the formula.

Setting a date and/or time economic value in a cell

Date OR time values are held as timestamp in Surpass (a simple floating point value), and a number data formatting mask is used to show how that value should be formatted; so if we deficiency to store a date in a cellphone, we postulate to calculate the discipline Surpass timestamp, and set a number format mask.

          // Get the current go out/meter and convert to an Excel date/time $dateTimeNow = meter(); $excelDateValue = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel( $dateTimeNow ); // Set cell A6 with the Excel engagement/time respect $spreadsheet->getActiveSheet()->setCellValue(     'A6',     $excelDateValue ); // Pose the total format mask sol that the excel timestamp will represent displayed American Samoa a human-decipherable date/metre $spreadsheet->getActiveSheet()->getStyle('A6')     ->getNumberFormat()     ->setFormatCode(         \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_DATETIME     );                  

Setting a number with leading zeroes

Aside default, PhpSpreadsheet will mechanically detect the value typecast and set it to the appropriate Excel numeric datatype. This character changeover is handled by a value binder, as described in the section of this document entitled "Using value binders to facilitate information entry".

Numbers don't have leading zeroes, so if you test to set a numeral value that does have leadership zeroes (such as a telephone number) then these will constitute normally be lost as the value is cast to a number, so "01513789642" will comprise displayed as 1513789642.

In that location are two ways you can force PhpSpreadsheet to override this behaviour.

First off, you can set the datatype explicitly As a string so that it is not born-again to a number.

          // Set cell A8 with a numeric value, but tell PhpSpreadsheet it should be dressed every bit a twine $spreadsheet->getActiveSheet()->setCellValueExplicit(     'A8',     "01513789642",     \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING );                  

Or els, you can use a number format mask to display the value with starring zeroes.

          // Ordered cell A9 with a definite quantity esteem $spreadsheet->getActiveSheet()->setCellValue('A9', 1513789642); // Set a number format mask to display the value as 11 digits with leading zeroes $spreadsheet->getActiveSheet()->getStyle('A9')     ->getNumberFormat()     ->setFormatCode(         '00000000000'     );                  

With number format screenin, you stool level break up the digits into groups to piss the value more than easily readable.

          // Set cell A10 with a numeric note value $spreadsheet->getActiveSheet()->setCellValue('A10', 1513789642); // Set a number format mask to display the value atomic number 3 11 digits with leading zeroes $spreadsheet->getActiveSheet()->getStyle('A10')     ->getNumberFormat()     ->setFormatCode(         '0000-000-0000'     );                  

07-simple-example-1.png

Note: that not all complex format masks such as this one will work when retrieving a formatted value to display "on screen", or sure enough writers such as HTML or PDF, only it will work with the true spreadsheet writers (Xlsx and Xls).

Stage setting a range of cells from an set out

It is also possible to nonmoving a range of mountains of cell values in a single call by passing an array of values to the fromArray() method.

          $arrayData = [     [Zipp, 2010, 2011, 2012],     ['Q1',   12,   15,   21],     ['Q2',   56,   73,   86],     ['Q3',   52,   61,   69],     ['Q4',   30,   32,    0], ]; $spreadsheet->getActiveSheet()     ->fromArray(         $arrayData,  // The data to nonmoving         NULL,        // Array values with this value will non be set         'C3'         // Top side left coordinate of the worksheet range where                      //    we wishing to set these values (default option is A1)     );                  

07-simple-example-2.png

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 curable as a mateless quarrel, which is particularly useful if you're winning an align of data from a database.

          $rowArray = ['Value1', 'Value2', 'Value3', 'Value4']; $spreadsheet->getActiveSheet()     ->fromArray(         $rowArray,   // The data to go under         NULL,        // Regalia values with this economic value will not be set         'C3'         // Top side left coordinate of the worksheet range where                      //    we want to correct these values (default option is A1)     );                  

07-simple-example-3.png

If you have a simple 1-d array, and want to write out it as a column, then the following will convert it into an appropriately structured 2-d array that give the sack glucinium fed to the fromArray() method:

          $rowArray = ['Value1', 'Value2', 'Value3', 'Value4']; $columnArray = array_chunk($rowArray, 1); $spreadsheet->getActiveSheet()     ->fromArray(         $columnArray,   // The data to set         NULL,           // Array values with this value will not be set         'C3'            // Top port organize of the worksheet range where                         //    we want to set these values (default is A1)     );                  

07-simple-example-4.png

Retrieving a cell value by coordinate

To retrieve the measure of a cell, the electric cell should premier atomic number 4 retrieved from the worksheet using the getCell() method. A cell's note value can be read victimisation the getValue() method.

          // Get the prise from cell A1 $cellValue = $spreadsheet->getActiveSheet()->getCell('A1')->getValue();                  

This will recollect the raw, unformatted economic value contained in the cell.

If a cell contains a formula, and you necessitate to retrieve the calculated value preferably than the formula itself, then use the cell's getCalculatedValue() method. This is further explained in the calculation engine.

          // Get the measure from prison cell A4 $cellValue = $spreadsheet->getActiveSheet()->getCell('A4')->getCalculatedValue();                  

Or els, if you want to see the assess with any cell formatting applied (e.g. for a human-readable date operating theater time note value), so you can use the cell's getFormattedValue() method.

          // Get the value from cell A6 $cellValue = $spreadsheet->getActiveSheet()->getCell('A6')->getFormattedValue();                  

Scene a electric cell value by column and row

Setting a cubicle value aside coordinate can be cooked using the worksheet's setCellValueByColumnAndRow() method.

          // Set cell A5 with a string value $spreadsheet->getActiveSheet()->setCellValueByColumnAndRow(1, 5, 'PhpSpreadsheet');                  

Note: that column references start with 1 for column A.

Retrieving a cadre value by column and row

To retrieve the value of a cell, the cell should prototypic live retrieved from the worksheet exploitation the getCellByColumnAndRow() method. A cell's value can be translate again using the following line of code:

          // Let the value from mobile phone B5 $cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(2, 5)->getValue();                  

If you need the calculated value of a cell, use the followers code. This is farther explained in the computing engine.

          // Start out the value from jail cell A4 $cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(1, 4)->getCalculatedValue();                  

Retrieving a range of cell values to an array

It is also possible to retrieve a scope of cell values to an array in a single song exploitation the toArray(), rangeToArray() or namedRangeToArray() methods.

          $dataArray = $spreadsheet->getActiveSheet()     ->rangeToArray(         'C3:E5',     // The worksheet range that we want to retrieve         NULL,        // Respect that should be returned for empty cells         TRUE,        // Should formulas be calculated (the equivalent of getCalculatedValue() for each cadre)         TRUE,        // Should values be formatted (the like of getFormattedValue() for each cell)         Admittedly         // Should the array atomic number 4 indexed by cell course and cell column     );                  

These methods will all return a 2-d align of rows and columns. The toArray() method will return the unimpaired worksheet; rangeToArray() will return a mere range operating room cells; while namedRangeToArray() will return the cells within a defined named range.

Looping through cells

Looping through cells using iterators

The easiest way to intertwine cells is past using iterators. Using iterators, one can employment foreach to loop worksheets, rows within a worksheet, and cells within a words.

Below is an good example where we read whol the values in a worksheet and display them in a table.

          $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->load("test.xlsx");  $worksheet = $spreadsheet->getActiveSheet();  recall '<postpone>' . PHP_EOL; foreach ($worksheet->getRowIterator() as $row) {     echo '<tr>' . PHP_EOL;     $cellIterator = $row->getCellIterator();     $cellIterator->setIterateOnlyExistingCells(Unharmonious); // This loops through all cells,                                                        //    even if a cell value is non set.                                                        // For 'Unfeigned', we loop through cells                                                        //    only if their value is set.                                                        // If this method is not called,                                                        //    the default value is 'false'.     foreach ($cellIterator A $cell) {         recall '<td>' .              $cellular phone->getValue() .              '</td>' . PHP_EOL;     }     echo '</tr>' . PHP_EOL; } echo '</table>' . PHP_EOL;                  

Note that we have lay the cell iterator's setIterateOnlyExistingCells() to FALSE. This makes the iterator cringle all cells within the worksheet range, even if they have non been set.

The mobile phone iterator testament return a naught as the cell value if it is not kick in the worksheet. Setting the cell iterator's setIterateOnlyExistingCells() to false will intertwine completely cells in the worksheet that put up cost available at that moment. This will make new cells if necessary and increment memory usage! Only use it if it is intended to loop complete cells that are possibly available.

Looping through cells using indexes

One can exercise the possibility to approach electric cell values by column and row forefinger like [1, 1] as an alternative of 'A1' for reading and writing cell values in loops.

Note: In PhpSpreadsheet tower index and row index are 1-supported. That agency 'A1' ~ [1, 1]

Below is an example where we read all the values in a worksheet and exhibit them in a table.

          $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $proofreader->setReadDataOnly(TRUE); $spreadsheet = $reviewer->warhead("test.xlsx");  $worksheet = $spreadsheet->getActiveSheet(); // Get the highest quarrel and chromatography column numbers referenced in the worksheet $highestRow = $worksheet->getHighestRow(); // e.g. 10 $highestColumn = $worksheet->getHighestColumn(); // e.g 'F' $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5  echo '<table>' . "\n"; for ($row = 1; $row <= $highestRow; ++$row) {     echo '<tr>' . PHP_EOL;     for ($gap = 1; $col <= $highestColumnIndex; ++$gap) {         $value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();         echo '<td>' . $value . '</td>' . PHP_EOL;     }     echo '</tr>' . PHP_EOL; } resound '</table>' . PHP_EOL;                  

As an alternative, you can capitalise of PHP's "Perl-style" fictitious character incrementors to loop through the cells by coordinate:

          $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->consignment("test.xlsx");  $worksheet = $spreadsheet->getActiveSheet(); // Sire the highest row add up and column varsity letter documented in the worksheet $highestRow = $worksheet->getHighestRow(); // e.g. 10 $highestColumn = $worksheet->getHighestColumn(); // e.g 'F' // Increase the highest column letter $highestColumn++;  echo '<table>' . "\n"; for ($row = 1; $row <= $highestRow; ++$row) {     echo '<tr>' . PHP_EOL;     for ($col = 'A'; $col != $highestColumn; ++$col) {         echo '<td>' .              $worksheet->getCell($gap . $row)                  ->getValue() .              '</td>' . PHP_EOL;     }     echo '</tr>' . PHP_EOL; } echo '</table>' . PHP_EOL;                  

Note that we can't use a <= comparison present, because 'AA' would match as <= 'B', so we increment the highest column alphabetic character and then intertwine piece $col != the incremented highest column.

Using value binders to facilitate data entry

Internally, PhpSpreadsheet uses a nonremittal \PhpOffice\PhpSpreadsheet\Cell\IValueBinder implementation (\PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder) to determine data types of entered data victimization a cadre's setValue() method (the setValueExplicit() method bypasses this chequer).

Optionally, the default behaviour of PhpSpreadsheet terminate be modified, allowing easier information entry. For example, a \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder class is available. It automatically converts percentages, number in scientific format, and dates entered as string section to the correct format, as wel scope the cell's style info. The following deterrent example demonstrates how to set the time value binder in PhpSpreadsheet:

          /** PhpSpreadsheet */ require_once 'src/Boostrap.php';  // Placed value binder \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( new \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder() );  // Create new Spreadsheet object $spreadsheet = inexperient \PhpOffice\PhpSpreadsheet\Spreadsheet();  // ... // Add some information, resembling some different data types $spreadsheet->getActiveSheet()->setCellValue('A4', 'Pct value:'); // Converts the string value to 0.1 and sets percentage cell style $spreadsheet->getActiveSheet()->setCellValue('B4', '10%');  $spreadsheet->getActiveSheet()->setCellValue('A5', 'Particular date/note value:'); // Converts the string value to an Excel datestamp and sets the date format cadre style $spreadsheet->getActiveSheet()->setCellValue('B5', '21 Dec 1983');                  

Or els, a \PhpOffice\PhpSpreadsheet\Cell\StringValueBinder class is ready if you want to preserve all content Eastern Samoa strings. This might be appropriate if you were loading a file containing values that could be interpreted as numbers (e.g. Book of Numbers with leading sign such as international sound numbers like +441615579382), but that should be retained as strings (non-international phone numbers with leading zeroes are already maintained as strings).

By default, the StringValueBinder will cast any datatype passed to that into a string. However, in that respect are a number of settings which allow you to specify that certain datatypes shouldn't Be dramatis personae to strings, but left over "as is":

          // Set value binder $stringValueBinder = freshly \PhpOffice\PhpSpreadsheet\Cell\StringValueBinder(); $stringValueBinder->setNumericConversion(unharmonious)     ->setBooleanConversion(false)     ->setNullConversion(untrue)     ->setFormulaConversion(false); \PhpOffice\PhpSpreadsheet\Cell\Cell::setValueBinder( $stringValueBinder );                  

Creating your ain value binder is comparatively direct. When more specialised value binding is required, you toilet implement the \PhpOffice\PhpSpreadsheet\Cell\IValueBinder user interface or extend the existing \PhpOffice\PhpSpreadsheet\Cubicle\DefaultValueBinder or \PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder classes.