### Install PhpSpreadsheet with Source Files Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/index.md Installs PhpSpreadsheet along with its documentation and sample files. This option requires 'git' to be available in your system's PATH. ```Shell composer require phpoffice/phpspreadsheet --prefer-source ``` -------------------------------- ### Install PhpSpreadsheet using Composer Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/index.md Installs the PhpSpreadsheet library into your project using Composer. This is the recommended method for managing dependencies. ```Shell composer require phpoffice/phpspreadsheet ``` -------------------------------- ### PhpSpreadsheet CellValue Wizard: Full Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/conditional-formatting.md A comprehensive example demonstrating the setup and application of multiple conditional formatting rules using the CellValue Wizard in PhpSpreadsheet. It includes setting rules for equals, greater than, and less than, applying styles, and setting the conditional styles to a cell range. ```php $cellRange = 'A2:E5'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\CellValue $cellWizard */ $cellWizard = $wizardFactory->newRule(Wizard::CELL_VALUE); $cellWizard->equals(0) ->setStyle($yellowStyle); $conditionalStyles[] = $cellWizard->getConditional(); $cellWizard->greaterThan(0) ->setStyle($greenStyle); $conditionalStyles[] = $cellWizard->getConditional(); $cellWizard->lessThan(0) ->setStyle($redStyle); $conditionalStyles[] = $cellWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($cellWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` -------------------------------- ### Install Development Dependencies (Composer) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/CONTRIBUTING.md Installs the necessary development dependencies for PhpSpreadsheet using Composer. This command should be run within the PhpSpreadsheet clone directory. ```shell composer install ``` -------------------------------- ### PhpSpreadsheet MINUTE Function Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Illustrates the usage of the MINUTE function in PhpSpreadsheet to get the minute component of a time value. The examples show setting cells with time strings and formulas, then retrieving the calculated minute. ```php $worksheet->setCellValue('A1', 'Time String') ->setCellValue('A2', '31-Dec-2008 17:30') ->setCellValue('A3', '14-Feb-2008 4:20 AM') ->setCellValue('A4', '14-Feb-2008 4:45 PM'); $worksheet->setCellValue('B2', '=MINUTE(A2)') ->setCellValue('B3', '=MINUTE(A3)') ->setCellValue('B4', '=MINUTE(A4)'); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 30 $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 20 $retVal = $worksheet->getCell('B4')->getCalculatedValue(); // $retVal = 45 ``` ```php $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'MINUTE'], ['09:30'] ); // $retVal = 30 ``` -------------------------------- ### PhpSpreadsheet DGET Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Shows how to use the DGET function to retrieve a single value from a database that matches specified criteria. The example includes setting up the database and criteria, populating the worksheet, and then fetching the calculated value. ```php /* DGET(database, field, criteria) database: The range of cells that makes up the list or database. field: Indicates which column of the database is used in the function. criteria: The range of cells that contains the conditions you specify. */ // Example usage would follow the same pattern as DCOUNT and DCOUNTA for setting up the worksheet and calling the function. ``` -------------------------------- ### Install Rector for PhpSpreadsheet Migration Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md Installs the necessary RectorPHP packages and PhpSpreadsheet for migrating a codebase from PHPExcel. This command ensures you have the correct versions of Rector and the target library to perform the automated migration. ```sh composer require rector/rector:0.15.10 rector/rector-phpoffice phpoffice/phpspreadsheet --dev # this creates rector.php config vendor/bin/rector init ``` -------------------------------- ### PHP Fluent Interface Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/architecture.md Demonstrates the use of fluent interfaces in PhpSpreadsheet to chain method calls for setting document properties, improving code readability and performance. ```PHP $spreadsheet->getProperties() ->setCreator("Maarten Balliauw") ->setLastModifiedBy("Maarten Balliauw") ->setTitle("Office 2007 XLSX Test Document") ->setSubject("Office 2007 XLSX Test Document") ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") ->setKeywords("office 2007 openxml php") ->setCategory("Test result file"); ``` -------------------------------- ### PhpSpreadsheet MONTH Function Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Provides examples of the MONTH function in PhpSpreadsheet, used to extract the month from a date. It demonstrates setting cells with date strings and formulas, then retrieving the calculated month. ```php $worksheet->setCellValue('A1', 'Date String'); $worksheet->setCellValue('A2', '31-Dec-2008'); $worksheet->setCellValue('A3', '14-Feb-2008'); $worksheet->setCellValue('B2', '=MONTH(A2)'); $worksheet->setCellValue('B3', '=MONTH(A3)'); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 12 $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 2 ``` ```php $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'MONTHOFYEAR'], ['14-July-2008'] ); // $retVal = 7 ``` -------------------------------- ### Install Redis Cache Adapters for PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/memory_saving.md Installs the required Composer packages for integrating Redis caching with PhpSpreadsheet, providing a robust solution for managing large datasets and reducing memory usage. ```sh composer require cache/simple-cache-bridge cache/redis-adapter ``` -------------------------------- ### PHP Spreadsheet DMIN Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Illustrates the DMIN function in PHP Spreadsheet for finding the minimum value in a database column that matches given conditions. The example shows how to set up the worksheet with data and criteria, apply the DMIN formula to a cell, and then fetch the computed result. ```php $database = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit' ], [ 'Apple', 18, 20, 14, 105.00 ], [ 'Pear', 12, 12, 10, 96.00 ], [ 'Cherry', 13, 14, 9, 105.00 ], [ 'Apple', 14, 15, 10, 75.00 ], [ 'Pear', 9, 8, 8, 76.80 ], [ 'Apple', 8, 9, 6, 45.00 ], ]; $criteria = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ], [ '="=Apple"', '>10', NULL, NULL, NULL, '<16' ], [ '="=Pear"', NULL, NULL, NULL, NULL, NULL ], ]; $worksheet->fromArray( $criteria, NULL, 'A1' ) ->fromArray( $database, NULL, 'A4' ); $worksheet->setCellValue('A12', '=DMIN(A4:E10,"Yield",A1:A3)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 6 ``` -------------------------------- ### Install APCu Cache Adapters for PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/memory_saving.md Installs the necessary Composer packages for using APCu as a cache backend with PhpSpreadsheet, enabling efficient memory management for large spreadsheets. ```sh composer require cache/simple-cache-bridge cache/apcu-adapter ``` -------------------------------- ### Instantiate Wizard Factory with Cell Range Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/conditional-formatting.md This example shows how to create an instance of the Wizard factory, providing the cell range ('C3:E5') where conditional formatting rules will be applied. This is the first step in defining conditional formatting rules using the Wizard API. ```php $wizardFactory = new \PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard('C3:E5'); $wizard = $wizardFactory->newRule(\PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard::CELL_VALUE); ``` -------------------------------- ### PHPSpreadsheet DPRODUCT Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Demonstrates the usage of the DPRODUCT function in PHPSpreadsheet to multiply values in a database column based on specified criteria. It involves setting up a database and criteria arrays, populating a worksheet, and then calculating the DPRODUCT. ```php $database = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit' ], [ 'Apple', 18, 20, 14, 105.00 ], [ 'Pear', 12, 12, 10, 96.00 ], [ 'Cherry', 13, 14, 9, 105.00 ], [ 'Apple', 14, 15, 10, 75.00 ], [ 'Pear', 9, 8, 8, 76.80 ], [ 'Apple', 8, 9, 6, 45.00 ], ]; $criteria = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ], [ '="=Apple"', '>10', NULL, NULL, NULL, '<16' ], [ '="=Pear"', NULL, NULL, NULL, NULL, NULL ], ]; $worksheet->fromArray( $criteria, NULL, 'A1' ) ->fromArray( $database, NULL, 'A4' ); $worksheet->setCellValue('A12', '=DPRODUCT(A4:E10,"Yield",A1:B2)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 140 ``` -------------------------------- ### Register and Create PDF Writer (Generic) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md This example shows how to register a specific PDF writer class (e.g., Mpdf) with a generic name ('Pdf') and then create a writer instance using that generic name. ```php $class = \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class; \PhpOffice\PhpSpreadsheet\IOFactory::registerWriter('Pdf', $class); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Pdf'); ``` -------------------------------- ### Install Memcache Cache Adapters for PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/memory_saving.md Installs the necessary Composer packages to enable Memcache caching within PhpSpreadsheet, aiding in the reduction of memory footprint for large file operations. ```sh composer require cache/simple-cache-bridge cache/memcache-adapter ``` -------------------------------- ### Rendering Charts with PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md Shows how to configure chart rendering in PhpSpreadsheet, specifically using the mitoteam/jpgraph library. It includes the composer command to install the library and the PHP code to set the chart renderer. ```sh composer require mitoteam/jpgraph ``` ```php Settings::setChartRenderer(\\PhpOffice\\PhpSpreadsheet\\Chart\\Renderer\\MtJpGraphRenderer::class); ``` -------------------------------- ### PHPSpreadsheet DSTDEV Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Illustrates the DSTDEV function in PHPSpreadsheet, which estimates the standard deviation of a population based on a sample. The example sets up a data range and criteria, then calculates the DSTDEV for the 'Yield' column. ```php $database = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit' ], [ 'Apple', 18, 20, 14, 105.00 ], [ 'Pear', 12, 12, 10, 96.00 ], [ 'Cherry', 13, 14, 9, 105.00 ], [ 'Apple', 14, 15, 10, 75.00 ], [ 'Pear', 9, 8, 8, 76.80 ], [ 'Apple', 8, 9, 6, 45.00 ], ]; $criteria = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ], [ '="=Apple"', '>10', NULL, NULL, NULL, '<16' ], [ '="=Pear"', NULL, NULL, NULL, NULL, NULL ], ]; $worksheet->fromArray( $criteria, NULL, 'A1' ) ->fromArray( $database, NULL, 'A4' ); $worksheet->setCellValue('A12', '=DSTDEV(A4:E10,"Yield",A1:A3)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 2.97 ``` -------------------------------- ### Create Conditional Formatting Rules with the Wizard in PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/conditional-formatting.md Illustrates using the PhpSpreadsheet Conditional Formatting Wizard to create rules based on cell values. This example shows how to set a 'less than' condition and apply font and fill styles to the rule. ```php $wizardFactory = new \PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard('A1:A10'); $wizard = $wizardFactory->newRule(\PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard::CELL_VALUE); $wizard->lessThan(10); $wizard->getStyle()->getFont()->getColor()->setARGB(\"PhpOffice\\PhpSpreadsheet\\Style\\Color::COLOR_DARKGREEN\"); $wizard->getStyle()->getFill()->setFillType(\"PhpOffice\\PhpSpreadsheet\\Style\\Fill::FILL_SOLID\"); $wizard->getStyle()->getFill()->getStartColor()->setARGB(\"PhpOffice\\PhpSpreadsheet\\Style\\Color::COLOR_GREEN\"); $conditional = $wizard->getConditional(); ``` -------------------------------- ### PhpSpreadsheet DCOUNT Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Demonstrates the usage of the DCOUNT function to count records in a dataset that match specific criteria. It involves setting up a data array, a criteria array, and then using PhpSpreadsheet methods to populate a worksheet and calculate the DCOUNT value. ```php $database = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit' ], [ 'Apple', 18, 20, 14, 105.00 ], [ 'Pear', 12, 12, 10, 96.00 ], [ 'Cherry', 13, 14, 9, 105.00 ], [ 'Apple', 14, 15, 10, 75.00 ], [ 'Pear', 9, 8, 8, 76.80 ], [ 'Apple', 8, 9, 6, 45.00 ], ]; $criteria = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ], [ '="=Apple"', '>10', NULL, NULL, NULL, '<16' ], [ '="=Pear"', NULL, NULL, NULL, NULL, NULL ], ]; $worksheet->fromArray( $criteria, NULL, 'A1' ) ->fromArray( $database, NULL, 'A4' ); $worksheet->setCellValue('A12', '=DCOUNT(A4:E10,"Height",A1:B3)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 3 ``` -------------------------------- ### Generating Excel from Template in PHP Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md Provides an example of loading an existing Excel template file, modifying cell values, and saving the changes to a new Excel file. This method is efficient for creating files with pre-defined styles and layouts. ```php $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx'); $worksheet = $spreadsheet->getActiveSheet(); $worksheet->getCell('A1')->setValue('John'); $worksheet->getCell('A2')->setValue('Smith'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls'); $writer->save('write.xls'); ``` -------------------------------- ### Calculate Sum with DSUM in PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Illustrates the usage of the DSUM function to sum values in a database column that meet specific criteria. The example sets up a database and criteria, populates the worksheet, and then calculates the DSUM. ```php $database = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit' ], [ 'Apple', 18, 20, 14, 105.00 ], [ 'Pear', 12, 12, 10, 96.00 ], [ 'Cherry', 13, 14, 9, 105.00 ], [ 'Apple', 14, 15, 10, 75.00 ], [ 'Pear', 9, 8, 8, 76.80 ], [ 'Apple', 8, 9, 6, 45.00 ], ]; $criteria = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ], [ '="=Apple"', '>10', NULL, NULL, NULL, '<16' ], [ '="=Pear"', NULL, NULL, NULL, NULL, NULL ], ]; $worksheet->fromArray( $criteria, NULL, 'A1' ) ->fromArray( $database, NULL, 'A4' ); $worksheet->setCellValue('A12', '=DMIN(A4:E10,"Profit",A1:A2)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 225 ``` -------------------------------- ### Configure Chart Renderer in PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/index.md Sets the chart rendering engine for PhpSpreadsheet. This is necessary for generating charts in HTML or PDF files, or rendering charts to image formats. You need to install either 'jpgraph/jpgraph' or 'mitoteam/jpgraph' via Composer. ```PHP // to use jpgraph/jpgraph Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph::class); //or // to use mitoteam/jpgraph Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer::class); ``` -------------------------------- ### PHP: Customizing empty row detection Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/Looping the Loop.md This example shows how to define custom rules for identifying empty rows in PhpSpreadsheet. It demonstrates how to treat null values and empty strings as empty cells by using predefined constants with the `isEmpty()` method. ```php if ($row->isEmpty( CellIterator::TREAT_EMPTY_STRING_AS_EMPTY_CELL | CellIterator::TREAT_NULL_VALUE_AS_EMPTY_CELL) ) { // Ignore empty rows continue; } ``` -------------------------------- ### PhpSpreadsheet IOFactory Identify to Verify File Type Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-files.md This example demonstrates using PhpSpreadsheet's IOFactory `identify()` method within a try-catch block to verify if a file matches a specific expected type (e.g., XLS). If the file does not match, a `PhpOffice\PhpSpreadsheet\Reader\Exception` is caught. ```php $inputFileName = './sampleData/example1.xls'; try { /** Verify that $inputFileName really is an Xls file **/ $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($inputFileName, [\PhpOffice\PhpSpreadsheet\IOFactory::READER_XLS]); } catch (\PhpOffice\PhpSpreadsheet\Reader\Exception $e) { // File isn't actually an Xls file, even though it has an xls extension } ``` -------------------------------- ### Run PhpSpreadsheet Samples (Shell) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/index.md Shows how to run PhpSpreadsheet sample scripts. This can be done by serving the samples directory via PHP's built-in web server or by executing individual sample scripts directly from the command line. ```sh php -S localhost:8000 -t vendor/phpoffice/phpspreadsheet/samples ``` ```sh php vendor/phpoffice/phpspreadsheet/samples/Basic/01_Simple.php ``` -------------------------------- ### Get AutoFilter Column Object Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/autofilters.md Retrieves an AutoFilter column object for a specified column ('C' in this example) from the active worksheet's AutoFilter instance. This object is used to apply filter expressions. ```php $autoFilter = $spreadsheet->getActiveSheet()->getAutoFilter(); $columnFilter = $autoFilter->getColumn('C'); ``` -------------------------------- ### Create Hello World Spreadsheet (PHP) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/index.md Demonstrates the simplest way to create an Excel spreadsheet (.xlsx) with 'Hello World!' in cell A1 using PhpSpreadsheet. It requires the PhpSpreadsheet library and its autoloader. ```php getActiveSheet(); $activeWorksheet->setCellValue('A1', 'Hello World !'); $writer = new Xlsx($spreadsheet); $writer->save('hello world.xlsx'); ``` -------------------------------- ### Use PhpSpreadsheet IOFactory to Create Reader Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-files.md This example shows how to use the PhpSpreadsheet IOFactory's `createReader()` method to dynamically instantiate a reader based on a provided file type string (e.g., 'Xls', 'Xlsx'). This method simplifies reader instantiation when the file type is known. ```php $inputFileType = 'Xls'; // $inputFileType = 'Xlsx'; // $inputFileType = 'Xml'; // $inputFileType = 'Ods'; // $inputFileType = 'Slk'; // $inputFileType = 'Gnumeric'; // $inputFileType = 'Csv'; $inputFileName = './sampleData/example1.xls'; /** Create a new Reader of the type defined in $inputFileType **/ $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType); /** Load $inputFileName to a Spreadsheet Object **/ $spreadsheet = $reader->load($inputFileName); ``` -------------------------------- ### Instantiate Specific Wizard Directly Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/conditional-formatting.md This code demonstrates an alternative method to create a Wizard instance directly, bypassing the factory. It shows how to instantiate the CellValue wizard for a specified cell range ('C3:E5'). ```php $wizard = new \PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\Wizard\CellValue('C3:E5'); ``` -------------------------------- ### Create Text Contains Conditional Rule using Wizard Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/conditional-formatting.md Shows how to create the same text contains conditional formatting rule ('LL') using the TextValue Wizard, which simplifies the process compared to manual creation. ```php $cellRange = 'A14:B16'; $conditionalStyles = []; $wizardFactory = new Wizard($cellRange); /** @var Wizard\TextValue $textWizard */ $textWizard = $wizardFactory->newRule(Wizard::TEXT_VALUE); $textWizard->contains('LL') ->setStyle($greenStyle); $conditionalStyles[] = $textWizard->getConditional(); $spreadsheet->getActiveSheet() ->getStyle($textWizard->getCellRange()) ->setConditionalStyles($conditionalStyles); ``` -------------------------------- ### Load Spreadsheet with Reader Configuration Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md Creates a reader instance for a file, allows configuration (e.g., read data only), and then loads the file. This provides more control over the reading process. ```php $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx"); $reader->setReadDataOnly(true); $reader->load("05featuredemo.xlsx"); ``` -------------------------------- ### PhpSpreadsheet DCOUNTA Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Illustrates the use of the DCOUNTA function to count non-blank cells within a specified column that meet given conditions. The example sets up a database and criteria, populates a worksheet, and then calculates the DCOUNTA value. ```php $database = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit' ], [ 'Apple', 18, 20, 14, 105.00 ], [ 'Pear', 12, 12, 10, 96.00 ], [ 'Cherry', 13, 14, 9, 105.00 ], [ 'Apple', 14, 15, 10, 75.00 ], [ 'Pear', 9, 8, 8, 76.80 ], [ 'Apple', 8, 9, 6, 45.00 ], ]; $criteria = [ [ 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ], [ '="=Apple"', '>10', NULL, NULL, NULL, '<16' ], [ '="=Pear"', NULL, NULL, NULL, NULL, NULL ], ]; $worksheet->fromArray( $criteria, NULL, 'A1' ) ->fromArray( $database, NULL, 'A4' ); $worksheet->setCellValue('A12', '=DCOUNTA(A4:E10,"Yield",A1:A3)'); $retVal = $worksheet->getCell('A12')->getCalculatedValue(); // $retVal = 5 ``` -------------------------------- ### Create New Spreadsheet (PHP) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/creating-spreadsheet.md Creates a new, empty PhpSpreadsheet workbook. Instantiating the `Spreadsheet` class directly creates a new workbook with a single default worksheet. ```php /** Create a new Spreadsheet Object **/ $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet(); ``` -------------------------------- ### PhpSpreadsheet Cell Referencing Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/accessing-cells.md Illustrates a potential issue with cell referencing in PhpSpreadsheet where assigning a cell to a variable can lead to detached references when other cells are accessed. This example shows how accessing cell 'A1' after 'C1' can affect the reference of the 'C1' variable. ```php $spreadSheet = new Spreadsheet(); $workSheet = $spreadSheet->getActiveSheet(); // Set details for the 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 '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; ``` -------------------------------- ### PhpSpreadsheet: Initialize and Bind Data Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/The Dating Game.md Initializes a new PhpSpreadsheet object, sets the active worksheet, and configures the Advanced Value Binder to handle data type conversions. It then writes project and weekly headings, followed by timesheet data and calculated durations. ```php use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Cell\Cell; use PhpOffice\PhpSpreadsheet\Cell\AdvancedValueBinder; use PhpOffice\PhpSpreadsheet\Style\Alignment; // Create new Spreadsheet object $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // Use the Advanced Value Binder so that our string date/time values will be automatically converted // to Excel serialized date/timestamps // Old method using static property Cell::setValueBinder(new AdvancedValueBinder()); // Preferred method using dynamic property since 3.4.0 $spreadsheet->setValueBinder(new AdvancedValueBinder()); // Write our data to the worksheet $worksheet->fromArray($projectHeading); $worksheet->fromArray($weekHeading, null, 'A3'); // Let Excel calculate the duration for each timesheet entry $row = 4; foreach ($timesheetData as $timesheetEntry) { ++$row; $worksheet->fromArray($timesheetEntry, null, "A{$row}"); $worksheet->setCellValue("D{$row}", "=C{$row} - B{$row}"); } $totalRow = $row + 2; $worksheet->setCellValue("D{$totalRow}", "=SUM(D4:D{$row})"); $worksheet->setCellValue("E{$totalRow}", 'Total Hours'); ``` -------------------------------- ### Conditional Formatting Mask Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/Behind the Mask.md This example demonstrates a conditional formatting mask that displays 'Fail' in red for values less than 65, and 'Pass' in blue otherwise. It utilizes square brackets for conditions and color codes. ```php $conditionalMask = '[Red][<65]"Fail";[Blue]"Pass"'; ``` -------------------------------- ### Read Symbolic Link (SYLK) Spreadsheet with PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md Illustrates the process of reading a Symbolic Link (.slk) file using PhpSpreadsheet's Slk reader, enabling data exchange with other applications. ```PHP $reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk(); $spreadsheet = $reader->load("05featuredemo.slk"); ``` -------------------------------- ### PHP: Skip header rows during iteration Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/Looping the Loop.md This code snippet shows how to adjust the starting row for iteration to skip header rows. By specifying a different starting row number in `getRowIterator`, you can begin processing data from the first actual data row. ```php $rowIterator = $worksheet->getRowIterator(3, $maxDataRow); ``` -------------------------------- ### Create Git Annotated Tag Source: https://github.com/phpoffice/phpspreadsheet/blob/master/CONTRIBUTING.md Creates an annotated Git tag for a new release. The tag subject should be the version number, and the body should contain the changelog entries. ```git git tag -a 1.2.3 Tag subject must be the version number, eg: 1.2.3 Tag body must be a copy-paste of the changelog entries. ``` -------------------------------- ### PhpSpreadsheet EOMONTH Function Example Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Illustrates the use of the EOMONTH function in PhpSpreadsheet to find the last day of a month, a specified number of months before or after a given date. The examples demonstrate setting cell values with EOMONTH formulas and retrieving calculated results, including date return type configuration. ```php $worksheet->setCellValue('A1', 'Date String') ->setCellValue('A2', '1-Jan-2000') ->setCellValue('A3', '14-Feb-2009'); $worksheet->setCellValue('B2', '=EOMONTH(A2,5)') ->setCellValue('B3', '=EOMONTH(A3,-12)'); \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType(\PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL); $retVal = $worksheet->getCell('B2')->getCalculatedValue(); // $retVal = 39629.0 (30-Jun-2008) $retVal = $worksheet->getCell('B3')->getCalculatedValue(); // $retVal = 39507.0 (29-Feb-2008) ``` ```php \PhpOffice\PhpSpreadsheet\Calculation\Functions::setReturnDateType( \PhpOffice\PhpSpreadsheet\Calculation\Functions::RETURNDATE_EXCEL ); $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'EOMONTH'], ['31-Oct-2008', 13] ); // $retVal = 40147.0 (30-Nov-2010) ``` -------------------------------- ### Update Worksheet::duplicateStyleArray Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md Shows the refactoring of `duplicateStyleArray` method for `Worksheet`. The functionality is now achieved by getting the style of a range and applying the array to it. ```php // Before $worksheet->duplicateStyleArray($styles, $range, $advanced); // After $worksheet->getStyle($range)->applyFromArray($styles, $advanced); ``` -------------------------------- ### Test Version Compatibility (Composer) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/CONTRIBUTING.md Tests the compatibility of the code with all supported PHP versions using Composer. This command helps ensure the code adheres to the project's version support policy. ```shell composer versions ``` -------------------------------- ### Create PDF Writer Instance (Mpdf) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md This code demonstrates how to create a PDF writer instance for PhpSpreadsheet, specifically using the 'Mpdf' library via the `IOFactory::createWriter` method. ```php $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf'); ``` -------------------------------- ### Get PhpSpreadsheet Excel Calendar Base Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Retrieves the current calendar setting used for calculating Excel date values. The default calendar is CALENDAR_WINDOWS_1900. ```php $baseDate = \PhpOffice\PhpSpreadsheet\Shared\Date::getExcelCalendar(); ``` -------------------------------- ### PhpSpreadsheet MID Function Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/references/function-list-by-category.md Returns a specific number of characters from a text string, starting at the position you specify, using PhpSpreadsheet's Extract::mid. Extracts a substring. ```php echo \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::mid($text, $startPos, $chars); ``` -------------------------------- ### PhpSpreadsheet LEFTB Function Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/references/function-list-by-category.md Returns the specified number of bytes from the start of a text string using PhpSpreadsheet's Extract::left. Useful for multi-byte character sets. ```php echo \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left($text, $bytes); ``` -------------------------------- ### Implement WORKDAY in PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/references/function-list-by-name-compact.md Maps the Excel WORKDAY function to the PhpSpreadsheet DateTimeExcel\WorkDay::date method, calculating a date that is a specified number of working days before or after a start date. ```php namespace PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel;\n\nclass WorkDay\n{\n const FUNCTION_NAME = 'WORKDAY';\n\n /**\n * @param mixed $startDate\n * @param int $days\n * @param array|null $holidays\n * @return mixed\n */\n public static function date($startDate, int $days, ?array $holidays = null)\n {\n // Implementation details for calculating work day\n return null; // Placeholder\n }\n} ``` -------------------------------- ### Convert Conditional to Wizard (Unknown Type) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/conditional-formatting.md Illustrates how to safely convert an unknown `Conditional` object to a Wizard using the `Wizard::fromConditional()` factory method. It demonstrates checking the returned Wizard type (e.g., `WizardCellValue`) and then applying specific rules, such as 'greater than', before converting it back to a new `Conditional` object. ```php $wizard = Wizard::fromConditional($conditional, '$A$3:$E$8'); if ($wizard instanceof Wizard\CellValue) { $wizard->greaterThan(12.5); $newConditional = $wizard->getConditional(); } ``` -------------------------------- ### Load Spreadsheet from File (PHP) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/creating-spreadsheet.md Loads an existing spreadsheet file into a PhpSpreadsheet object. Requires the file path as input. This method utilizes the IOFactory to handle different file formats. ```php $inputFileName = './sampleData/example1.xls'; /** Load $inputFileName to a Spreadsheet object **/ $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName); ``` -------------------------------- ### Get PhpSpreadsheet Date Return Type Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Retrieves the current data type setting for returning date values from Excel functions. The default return type is RETURNDATE_PHP_NUMERIC. ```php $returnDateType = \PhpOffice\PhpSpreadsheet\Calculation\Functions::getReturnDateType(); ``` -------------------------------- ### Get Smallest Value (SMALL) Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/references/function-list-by-category.md Returns the k-th smallest value in a data set. This function is useful for finding specific order statistics within a range of data. ```php namespace PhpOffice\PhpSpreadsheet\Calculation\Statistical\Size; class Size { const small = 'small'; } ``` -------------------------------- ### PhpSpreadsheet HOUR Function Usage Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Provides an example of the HOUR function in PhpSpreadsheet, which extracts the hour component from a given date/time value. The function returns an integer between 0 and 23. ```php The HOUR function returns the hour of a time value. The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.). ##### Syntax HOUR(datetime) ##### Parameters **datetime** Time. An Excel date/time value, PHP date timestamp, PHP `DateTime` object, or a date/time represented as a string. ##### Return Value **integer** An integer value that reflects the hour of the day. This is an integer ranging from 0 to 23. ``` -------------------------------- ### CSV Constructor Callback Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md Sets a callback function to configure default CSV reader attributes upon instantiation, allowing for custom initialization logic. ```php function constructorCallback(\PhpOffice\PhpSpreadsheet\Reader\Csv $reader): void { $reader->setInputEncoding(\PhpOffice\PhpSpreadsheet\Reader\Csv::GUESS_ENCODING); $reader->setFallbackEncoding('ISO-8859-2'); $reader->setDelimiter(','); $reader->setEnclosure('"'); // Following represents how Excel behaves better than the default escape character $reader->setEscapeCharacter(''); } \PhpOffice\PhpSpreadsheet\Reader\Csv::setConstructorCallback('constructorCallback'); $spreadsheet = \PhpSpreadsheet\IOFactory::load('sample.csv'); ``` -------------------------------- ### Edit HTML During Save via Callback Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/reading-and-writing-to-file.md This example shows how to use a callback function with `setEditHtmlCallback()` to modify the generated HTML content before saving, such as changing border styles. ```php function changeGridlines(string $html): string { return str_replace('{border: 1px solid black;}', '{border: 2px dashed red;}', $html); } $writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet); $writer->setEditHtmlCallback('changeGridlines'); $writer->save($filename); ``` -------------------------------- ### PhpSpreadsheet LEFT Function Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/references/function-list-by-category.md Returns the specified number of characters from the start of a text string using PhpSpreadsheet's Extract::left. Extracts characters from the left side of a string. ```php echo \PhpOffice\PhpSpreadsheet\Calculation\TextData\Extract::left($text, $chars); ``` -------------------------------- ### Writing PDF with PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md Demonstrates how to write PDF files using PhpSpreadsheet, including registering a PDF writer and creating a PDF writer instance. This replaces the older PHPExcel methods for PDF rendering. ```php $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf'); ``` ```php $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Pdf'); ``` ```php $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet); ``` -------------------------------- ### PhpSpreadsheet DROP Function Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/references/function-list-by-name-compact.md Maps the Excel DROP function to PhpSpreadsheet's LookupRefChooseRowsEtc::drop class for removing a specified number of rows or columns from the start or end of an array. ```php namespace PhpOffice\PhpSpreadsheet\Calculation\LookupRef; class ChooseRowsEtc { public static function drop(array $array, int $rows, int $cols = 0): } ``` -------------------------------- ### Get Default Timezone Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Retrieves the current default timezone that PhpSpreadsheet uses for handling date and time conversions. The default timezone is typically UST (Universal Standard Time). ```PHP use \PhpOffice\PhpSpreadsheet\Shared\Date;\n\n$defaultTimezone = Date::getDefaultTimezone(); ``` -------------------------------- ### Run Rector Migration Process Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/migration-from-PHPExcel.md Executes the RectorPHP migration process on the specified source code directory. This command applies the configured rules to automatically update the codebase from PHPExcel to PhpSpreadsheet. ```sh vendor/bin/rector process src ``` -------------------------------- ### JpGraph Integration with PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/src/PhpSpreadsheet/Chart/Renderer/PHP Charting Libraries.txt Demonstrates the integration of JpGraph charting library with PhpSpreadsheet, highlighting the use of composer packages for rendering charts. ```PHP require_once 'vendor/autoload.php'; use PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph; use PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer; // Example usage with JpGraph renderer // $spreadsheet = new Spreadsheet(); // $sheet = $spreadsheet->getActiveSheet(); // $chart = new Chart(); // $chart->setRenderer(new JpGraph()); // Example usage with MtJpGraphRenderer // $chart->setRenderer(new MtJpGraphRenderer()); ``` -------------------------------- ### Negative Binomial Distribution Function in PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/references/function-list-by-category.md Implements the negative binomial distribution, which models the number of trials needed to get a specified number of successes. This is a type of binomial distribution. ```PHP \PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\Binomial::negative ``` -------------------------------- ### Calculate Days360 with Excel Timestamps using PhpSpreadsheet Source: https://github.com/phpoffice/phpspreadsheet/blob/master/docs/topics/calculation-engine.md Demonstrates the usage of the DAYS360 function in PhpSpreadsheet with Excel date timestamps. It includes examples for both the U.S. (NASD) method and the European method. ```php $date1 = 37655.0; // Excel timestamp for 25-Oct-2007 $date2 = 39233.0; // Excel timestamp for 8-Dec-2015 $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DAYS360'], [$date1, $date2] ); // $retVal = 1558 $retVal = call_user_func_array( ['\PhpOffice\PhpSpreadsheet\Calculation\Functions', 'DAYS360'], [$date1, $date2, TRUE] ); // $retVal = 1557 ```